【问题标题】:Change current working directory in child process in C在C中更改子进程中的当前工作目录
【发布时间】:2018-05-22 12:37:15
【问题描述】:

我必须编写一个程序来生成子进程而不是结束父进程,然后创建的子进程必须要求用户输入新的工作目录,更改它并打印到其新工作目录的路径。我写了这个,但是 scanf 不起作用(“它不是要求用户输入内容,程序刚刚结束)并且路径没有改变......我试图将新目录设置为 char *newdirectory="home/usr/desktop" 并且没有改变工作目录也是

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>

int main()
{
    int pid;
    char directory[1024];
    char newdirectory[1024];        
    pid=fork(); 
    if(pid<0)
    {
        printf("\n Error ");
        exit(1);
    }
    else if(pid==0)
    {
        printf("I'm child \n ");
        printf(" My PID: %d \n",getpid());
        getcwd(directory, sizeof(directory));
        printf(" My current working directory is: %s\n", directory);
        printf(" Enter the new path\n");
        scanf("%s", &newdirectory);
        chdir(newdirectory);
        getcwd(directory, sizeof(directory));
        printf(" Path changed to: %s\n", directory);
        exit(0);
    }
    else
    {
        printf("I'm a parent \n ");
        printf("My PID is %d \n ",getpid());
        printf("Bye bye \n");
        exit(1);
    }
    return 0;
}

感谢您的时间、精力和所有帮助理解:)

【问题讨论】:

  • “不工作”不是一个有用的问题描述。如果你把车开给修理工,你会不会说“它不工作了!”然后走出门期待车修好?
  • @AndrewHenle 修正描述:)

标签: c fork scanf chdir getcwd


【解决方案1】:

你有两个错误,

  • scanf() 的用法
  • 不等待孩子完成其作为父母的任务。

以下工作。

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>

int main()
{
    int pid;
    char directory[1024];
    char newdirectory[1024];
    pid=fork();
    if(pid<0)
    {
        printf("\n Error ");
        exit(1);
    }
    else if(pid==0)
    {
        printf("I'm child \n ");
        printf(" My PID: %d \n",getpid());
        getcwd(directory, sizeof(directory));
        printf(" My current working directory is: %s\n", directory);
        printf(" Enter the new path\n");
        scanf("%1023s", newdirectory);
        chdir(newdirectory);
        getcwd(directory, sizeof(directory));
        printf(" Path changed to: %s\n", directory);
        exit(0);
    }
    else
    {
        wait(0);
        printf("I'm a parent \n ");
        printf("My PID is %d \n ",getpid());
        printf("Bye bye \n");
        exit(1);
    }
}

【讨论】:

  • 首先非常感谢您!它正在工作,我理解一切,但有一个问题要问你在任务描述中写道:“父进程必须生成子进程,在子进程做任何事情之前,父进程必须结束它的“生命””,在父进程死后,子进程必须要求新路径等。我认为这是任务描述中的错误,因为在我看来我们将创建一个孤立的进程,但我不是 100% 确定......你怎么看?
  • @szeejdi 是的,我同意你的看法。该案例导致孤儿进程。 在孩子做任何事情之前,父母必须结束它的“生命””是错误的。
  • 好的 :D 谢谢,我会接受你的回答作为解决方案:)
猜你喜欢
  • 2011-03-29
  • 2020-06-05
  • 1970-01-01
  • 2014-01-14
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多