在這個程序中,爲什麼子進程打印錯誤ppid()?子進程打印出錯ppid()
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void childprocess()
{
printf("Child: Hi I am the child process\n");
printf("Child: My process id is %d\n", getpid());
printf("Child: My parent is %d\n", getppid());
printf("Child: I am exiting\n");
}
void parentprocess()
{
printf("Parent: Hi I am the parent process\n");
printf("Parent: My process id is %d\n", getpid());
printf("Parent: My parent is %d\n", getppid());
printf("Parent: I am exiting\n");
}
int main()
{
pid_t n = fork();
if(n<0)
{
perror("fork failed:");
exit(EXIT_FAILURE);
}
else if(n==0)
childprocess();
else
parentprocess();
}
輸出:
Parent: Hi I am the parent process
Parent: My process id is 21550
Parent: My parent is 7452
Parent: I am exiting
Child: Hi I am the child process
Child: My process id is 21551
Child: My parent is 1810
Child: I am exiting
如果我重新執行。有時輸出是我所期望的,有時卻是意想不到的。
嘗試添加一些sleep();在父進程中,我想你會得到你所期望的。這個問題可能是https://en.wikipedia.org/wiki/Orphan_process –