Beg*_*ner 2 linux ubuntu system-calls fork
我的代码正在分叉一个进程并打印每个进程的 PID 和 PPID。我期待孩子的 PPID 与父母的 PID 相同,但事实并非如此。
我正在使用 Ubuntu 14.04。
#include <stdio.h>
#include <sys/wait.h>
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;
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
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
Run Code Online (Sandbox Code Playgroud)
我的猜测是:父母在孩子之前回来,孩子成了孤儿。PID 1135 必须是您的用户 init 进程,它成为该进程的新父进程。(Ubuntu 用户会话中有 2 个子收割者)。
$ ps -ef | grep init
you 1135 ... init --user
Run Code Online (Sandbox Code Playgroud)
如果您希望您的父母等待其孩子,请使用wait
. 您实际上已经拥有include
:
#include <stdio.h>
#include <sys/wait.h>
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;
}
Run Code Online (Sandbox Code Playgroud)
这将确保父级不会在子级printf
. 通过sleep()
在这里和那里插入一些调用来查看事情发生的顺序,您可以更清楚地看到这种行为。
有关子收割者的更多信息,请查看此处。
归档时间: |
|
查看次数: |
543 次 |
最近记录: |