,而不是你的代码,试试这个:
#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()'的结果,您就可以构建整个流程层次结构。 –