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