如何处理分支出来,当你在使用fork()循环? [英] How do processes branch out when you use fork() in a for loop?

查看:228
本文介绍了如何处理分支出来,当你在使用fork()循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

叉()循环外线电话都容易弄清楚,但是当他们在一个循环中我觉得很难。任何人都可以形象地解释如何处理分支与像这样的例子吗?

 的#include<&stdio.h中GT;诠释主(){
    INT I;
    对于(I = 0; I&2;我+ +)
    {
        叉子();
        的printf(HI);
        叉子();
    }
    出口(0);
}


解决方案

在理想情况下,这将是这样的:


  • 还有就是喜印有每个过程中的一个(简称PROC)

  • 每个叉双打过程中(每个进程生成一个孩子)

的计算可以通过每个事件如下进行:


  • 启动:1 PROC

  • 叉:2×1 = 2的特效

  • 打印:2特效 - > 2喜公司

  • 叉:2×2 = 4的特效

  • 叉:2×4 = 8特效

  • 打印:8特效 - > 八喜的

  • 叉:2×8的特效 - > 16特效

现在我们加起来喜公司的数量:

2 + 8 = 10喜公司合计

然而,这并不一定是这样。在不同的系统,你可能会得到不同的结果。

要调用fork()会导致催生了一个子进程是相同的父。
如果有任何的缓存的标准输出打印完成时和缓冲区不会被刷新下叉之前,那么孩子就会出现打印时,不应该。请参照<一个href=\"http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin\"标题=此>有关缓冲的一些细节这个问题

这会导致打印的不同系统不同数量的喜公司的。

fork() calls outside a loop are easy to figure out, but when they are inside a loop I find it difficult. Can anyone figuratively explain how the processes branch out with an example like this one?

#include <stdio.h>

int main(){
    int i; 
    for(i=0;i<2;i++)
    {
        fork();
        printf("hi");
        fork();
    }
    exit(0);
}

解决方案

Ideally, this would be the case:

  • There is one "hi" printed with each process (abbreviated as proc)
  • Each fork doubles the number of process (each process spawns one child)

The calculation could be done by following each event:

  • start: 1 proc
  • fork: 2 x 1 = 2 procs
  • print: 2 procs -> 2 hi's
  • fork: 2 x 2 = 4 procs
  • fork: 2 x 4 = 8 procs
  • print: 8 procs -> 8 hi's
  • fork: 2 x 8 procs -> 16 procs

Now we add up the the number of hi's:

2 + 8 = 10 hi's in total

However, this is not necessarily the case. On different systems, you may get different results.

A call to fork() causes a child process to be spawned that is identical to the parent. If there is any buffering done when printing stdout and the buffers are not flushed before the next fork, then the child will appear to print when it "should not have". Refer to this question for some details on buffering.

This causes a different number of hi's to be printed an different systems.

这篇关于如何处理分支出来,当你在使用fork()循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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