【问题标题】:Understanding the fork() command Posix API理解 fork() 命令 Posix API
【发布时间】:2015-01-01 01:03:50
【问题描述】:
#include<iostream>
#include<unistd.h>
#include<stdio.h>
using namespace std;
int main()
{
    fork();
    fork();
    fork();
    fork();
    printf("*"); /*This prints 16 stars*/ 
    return 0;
}

使用fork() 时,为什么会打印16 个*?

我了解fork() 会生成一个新的 两个子进程都执行相同的进程,这可以解释为什么一个分叉会生成 2 颗星,但是,如果有四个分叉,它会打印 16 个,我可以看到每个fork() 都会加倍。

但我不明白为什么。每个 fork 是否执行它下面的函数和参数?

【问题讨论】:

  • How does fork() work?的可能重复
  • 还有无数其他人。 (大部分因故而被删除。)
  • 无论如何using namespace std; 在 C 程序中?在 C++ 中已经够糟糕了。
  • 我会记住的!
  • 我将投票保持开放,因为父子节点中的重复分叉以指数速度增加。我认为该解释将有助于 OP 和未来的访问者深入了解流程总和的实际情况。

标签: c posix


【解决方案1】:

因为第一个 fork 将分成两个进程,第二个 fork() 调用将由这两个进程调用,将这两个进程分成 4 个。这将一直持续到每个进程中的所有 fork() 调用都被调用.所以你最终会得到2^4 = 16printf("*") 的调用

在“图表”中,每个条形代表调用函数时正在执行的进程数。所以函数的执行次数与条数一样多。

       |   fork()             // The first processes creates a second (2 total)
       |   fork()    |        // Those 2 processes start 2 more       (4 total)
      ||   fork()    ||       // Those 4 processes start 4 more       (8 total)
    ||||   fork()    ||||     // Those 8 processes start 8 more       (16 total) 
||||||||  printf()   |||||||| // resulting in 16 calls to printf()

每个fork是否都在执行它下面的函数和参数?

是的,从图中可以看出,当一个进程对创建的进程(以及创建它的进程)进行分叉时,会继续执行分叉后的下一条指令。

【讨论】:

  • 清晰的描述,你给了一个很好的解释!
【解决方案2】:

当你调用 fork() 时,它会创建一个新进程。您复制您的应用程序,然后 2 个应用程序继续运行并在 fork() 调用后执行新指令

printf("i'm the main thread\n");
fork();
printf("i'm executed 2 times\n");
fork(); //this fork is so executed 2 times, so 2 new processes, so 4 processes for all
printf("i'm excecuted 4 times\n");
fork(); //this fork is executed 4 times to ! So you have now 8 processes;
// and etc ..
fork(); //this fork is executed 8 times, 16 process now !
printf("*"); // executed 16 times

新进程共享所有内存在 fork() 之前,旧的更改状态用于当前线程。 如果您想根据流程做其他事情:

pid_t p;
int i = 1;
p = fork();
if(p == 0)
{
    printf("I'm the child\n");
    i = 2;
    exit(0); //end the child process
 }
 printf("i'm the main process\n");
 printf("%d\n", i); //print 1

【讨论】:

  • 请注意,fork() 创建的是进程,而不是线程。所以I'm the main thread的评论有点不对。
猜你喜欢
  • 2016-11-01
  • 1970-01-01
  • 2017-06-21
  • 2018-07-07
  • 2016-01-21
  • 2014-02-14
  • 1970-01-01
  • 2023-02-16
  • 2016-10-29
相关资源
最近更新 更多