理解fork()的命令Posix的API [英] Understanding the fork() command Posix API

查看:146
本文介绍了理解fork()的命令Posix的API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #包括LT&;&iostream的GT;
#包括LT&;&unistd.h中GT;
#包括LT&;&stdio.h中GT;
使用命名空间std;
诠释的main()
{
    叉子();
    叉子();
    叉子();
    叉子();
    的printf(*); / *这将打印16星* /
    返回0;
}

工作时叉(),为什么它打印16 *的?

据我所知,叉()生成新
子进程都执行相同的过程,可以解释为什么一把叉子产生2星,但它打印16四面叉,我可以看到,它与每个叉双打()

但我不理解为什么。在每个叉执行它下面的功能和参数?


解决方案

由于第一叉将分为两个过程,第二个叉()通话将被称为这两个过程,分裂这两个进程进入4。这将继续下去,直到所有的fork()的调用已在每个过程调用。所以,你最终不得不 2 ^ 4 = 16 的printf调用(*)

在图各条重presents时调用函数时正在执行的进程数。因此,功能一样有酒吧多次执行。

  |叉()//第一进程会创建第二个(2个)
       |叉()| //那些2个进程启动2个(共4个)
      ||叉()|| //这4个过程将开始,4个(共8个)
    |||| fork()的|||| //这8过程将开始,8个(16个)
|||||||| printf()的|||||||| //造成16调用的printf()


  

时的每一个叉执行它下面的功能和参数?


是的,你可以从图中,当一个进程派生创建的过程(以及创建它的一个)继续上叉后的下一个指令执行看到的。

#include<iostream>
#include<unistd.h>
#include<stdio.h>
using namespace std;
int main()
{
    fork();
    fork();
    fork();
    fork();
    printf("*"); /*This prints 16 stars*/ 
    return 0;
}

When working with fork(), why does it print 16 *'s?

I understand that fork() generates a new child process that both execute the same process which would explain why one fork generates 2 stars but, with four forks it prints 16 which I can see that it doubles with each fork().

But I am not understanding why. Is each fork executing the functions and parameters below it?

解决方案

Because the first fork will split into two process, the second fork() call will be called by those two processes, splitting those two processes into 4. This will continue until all the fork() calls have been called in each process. So you end up having 2^4 = 16 calls to printf("*")

In the "diagram" each bar represents the number of processes that are executing when the function is called. So the function is executed as many times as there are bars.

       |   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()

Is each fork executing the functions and parameters below it?

Yes, as you can see from the diagram, when a process forks the created process (and the one that created it) continues execution on the next instruction after the fork.

这篇关于理解fork()的命令Posix的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆