这是我的 fork() 系统调用代码,
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
int main(int argc, char *argv[])
{
pid_t pid;
pid=fork();
printf("1st Fork\n");
printf("Process ID : %d, Parent Process ID : %d\n",getpid(),getppid());
pid=fork();
printf("2nd Fork\n");
printf("Process ID : %d, Parent Process ID : %d\n",getpid(),getppid());
pid=fork();
printf("3rd Fork\n");
printf("Process ID : %d, Parent Process ID : %d\n",getpid(),getppid());
return 0;
}
在运行代码时,我得到如下输出
1st Fork
Process ID : 3393, Parent Process ID : 3392
2nd Fork
Process ID : 3394, Parent Process ID : 3393
3rd Fork
Process ID : 3395, Parent Process ID : 3394
3rd Fork
Process ID : 3394, Parent Process ID : 3393
2nd Fork
Process ID : 3393, Parent Process ID : 3392
3rd Fork
Process ID : 3397, Parent Process ID : 3393
3rd Fork
Process ID : 3393, Parent Process ID : 3392
1st Fork
Process ID : 3392, Parent Process ID : 3440
2nd Fork
Process ID : 3398, Parent Process ID : 3392
3rd Fork
Process ID : 3400, Parent Process ID : 3398
3rd Fork
Process ID : 3398, Parent Process ID : 3392
2nd Fork
Process ID : 3392, Parent Process ID : 3440
3rd Fork
Process ID : 3401, Parent Process ID : 3392
3rd Fork
Process ID : 3392, Parent Process ID : 3440
为什么这个 fork() 系统调用会产生 8 个进程,如何进行?
我还执行了 14 次 printf() 语句。为什么?
最佳答案
每次你调用 fork
它都会返回两次。一次在父进程中,一次在新进程中。然后,随着它们的继续,它们再次 fork 。
很可能您没有预料到 children 会再次 fork 。对于每个 fork
,您通常有:
switch (fork()) {
case -1:
/* ERROR. */
break;
case 0:
/* Child process. */
break;
default:
/* Parent. */
break;
}
在你的代码中是这样的:
- 您有一个进程,然后它 fork
- 您现在有两个进程并且都派生
- 您现在有 4 个进程并且所有进程都 fork
- 您现在有 8 个流程,并且您正在就 SO 提问
关于c - 以什么方式,fork() 系统调用生成子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8397816/