我的代码是分支进程并打印每个进程的PID和PPID.我期待孩子的PPID与父母的PID相同,但它不是这样的.
我正在使用Ubuntu 14.04.
#include
#include
int main(){
int pid;
pid = fork();
if(pid==0){
printf("\nI am the child and my parent id is %d and my id %d\n", getppid(), getpid());
}
else
printf("\nI am the parent and my pid is %d and my parent id is %d\n", getpid(), getppid());
return 0;
}
这是我得到的输出:
I am the parent and my pid is 29229 and my parent id is 27087
I am the child and my parent id is 1135 and my id is 29230
解决方法:
我的猜测是:父母在孩子面前回来,后来变成了一个孤儿. PID 1135必须是您的用户初始化进程,该进程成为进程的新父进程. (Ubuntu用户会话中有2个subreapers).
$ps -ef | grep init
you 1135 ... init --user
如果您希望您的父母等待其孩子,请使用等待.你实际上已经有了包括:
#include
#include
int main(){
int pid;
pid = fork();
if(pid == 0)
printf("\nI am the child and my parent id is - %d and mine id %d\n",getppid(),getpid());
else{
printf("\nI am the parent and my pid is %d and my parent id is %d\n",getpid(),getppid());
wait(NULL);
}
return 0;
}
这将确保父级不会在子级的printf之前退出.您可以通过在此处插入一些sleep()调用来更清楚地看到此行为,以查看事件发生的顺序.
有关subreapers的更多信息,请参见have a look here.
标签:linux,ubuntu,system-calls,fork
来源: https://codeday.me/bug/20190814/1653651.html