在 C 中更改子进程中的当前工作目录

Change current working directory in child process in C

我必须编写一个程序来生成子进程而不是结束父进程,然后创建的子进程必须要求用户输入新的工作目录,更改它并打印到其新工作目录的路径。我写了这个,但是 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;
}

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

你有两个错误,

  • scanf()
  • 的用法
  • 没有等待 child 作为 parent 完成任务。

以下作品。

#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);
    }
}