我必须编写一个程序来生成子进程而不是结束父进程,然后创建的子进程必须要求用户输入新的工作目录,更改它并打印到其新工作目录的路径。我写了这个,但是 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;
}
感谢您的时间、精力和所有帮助理解 :)