c - 以什么方式,fork() 系统调用生成子进程?

标签 c unix fork

这是我的 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/

相关文章:

c - 从 exec 系统调用返回时使用 iret

linux - 在 Bash 脚本中过滤类型错误的正确方法是什么?

c - ipv6迁移的副作用

linux - 如何在 Linux(Fedora-20) 中使用 find 命令的目录参数

c++ - fork进程之间的随机数是相同的

c - 为什么 gets() 假设 extern 在 C 代码中返回 int?

c - recvfrom() 不阻塞

c - 转移 __m128i 的最佳方法?

git - 当上游未接受我的 pull 请求时,我可以删除 fork 的 Github 存储库吗?

cat/Xargs/command VS for/bash/command