,而不是你的代碼,試試這個:
#include <stdio.h>
#include <unistd.h>
int main()
{
int counter = 0;
if(fork())
{
// should be the parent
fprintf(stderr, "1. process ID: %d\n", getpid());
fprintf(stderr, "1. parent process ID: %d\n", getppid());
++counter;
}
else
if(fork())
{
fprintf(stderr, "2. process ID: %d\n", getpid());
fprintf(stderr, "2. parent process ID: %d\n", getppid());
--counter;
}
else
{
fprintf(stderr, "3. process ID: %d\n", getpid());
fprintf(stderr, "3. parent process ID: %d\n", getppid());
++counter;
}
printf("counter: %d\n", counter);
}
這裏是運行代碼的輸出:
ALP ❱ gcc temp.c
ALP ❱ ./a.out
1. process ID: 6672
1. parent process ID: 3037
counter: 1
2. process ID: 6673
2. parent process ID: 6672
counter: -1
3. process ID: 6674
3. parent process ID: 2008
counter: 1
ALP ❱ ps
PID TTY TIME CMD
3037 pts/2 00:00:01 bash
5354 pts/2 00:00:00 redshift
6642 pts/2 00:00:00 ps
ALP ❱ ps -e | grep 2008
2008 ? 00:00:00 upstart
ALP ❱
現在正在發生的事情是這樣的:
3037
是bash我的機器上的進程ID 2008
是進程ID upstart
(=照顧zombi這裏的電子處理)
6672
是main
功能
6673
的進程ID爲第一子過程及其父母是主要:6672
6674
是第二子過程和2008
(=暴發戶)成爲其父母
雖然我不知道,但我猜你有子進程沿着主,因此共3個。由於您沒有檢查-1
調用fork(2)
的失敗,所以在運行代碼的其他人可能會有所不同。
注意
因爲你爲你的孩子和主要出口不wait(2)
不終止它們,upstart(8)
需要終止他們的照顧。
注2:
以這種方式,則不應使用fork(2)
。
將printf更改爲顯示'printf(「i =%d,pid =%d \ n」,i,getpid());'你將自己得到答案。或者,更好的方法是打印'getppid()'的結果,您就可以構建整個流程層次結構。 –