7
我運行程序爲什麼getppid()從孩子返回1
#include<stdio.h>
#include <unistd.h>
main()
{
pid_t pid, ppid;
printf("Hello World1\n");
pid=fork();
if(pid==0)
{
printf("I am the child\n");
printf("The PID of child is %d\n",getpid());
printf("The PID of parent of child is %d\n",getppid());
}
else
{
printf("I am the parent\n");
printf("The PID of parent is %d\n",getpid());
printf("The PID of parent of parent is %d\n",getppid());
}
}
輸出我得到了。
$ ./a.out
Hello World1
I am the parent
The PID of parent is 3071
The PID of parent of parent is 2456
I am the child
The PID of child is 3072
The PID of parent of child is 1
我不可能不懂行
孩子的家長的PID爲1
應該已經3071?
你可以通過添加適當的fflush(NULL);(在fork之前)和sleep(1);調用(在if和else的一部分中)來觀察你期望的行爲,就在'main'結束之前)。 –