我的程式碼是分叉一個進程並列印每個進程的 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;
}
這是我得到的輸出:
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
答案1
我的猜測是:父母先於孩子回來,孩子成了孤兒。 PID 1135 必須是您的使用者 init 進程,它成為該進程的新父進程。 (Ubuntu 使用者會話中有 2 個子收割機)。
$ ps -ef | grep init
you 1135 ... init --user
如果您希望父母等待其孩子,請使用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;
}
這將確保父級不會在子級之前退出printf
。透過到處插入一些sleep()
呼叫來查看事情發生的順序,您可以更清楚地看到這種行為。
有關分收割機的更多信息,看看這裡。