fork()的分支机构超过预期? [英] fork() branches more than expected?

查看:96
本文介绍了fork()的分支机构超过预期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的一块code的:

Consider the following piece of code:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    int i;
    for(i = 0; i < 2; i++)
    {
        fork();
        printf(".");
    }
    return 0;
}

此程序输出8点。这怎么可能?不应该有6点呢?

This program outputs 8 dots. How can that be possible? Should not there be 6 dots instead?

推荐答案

叉()原始往往延伸的想象力。直到你得到它的感觉,你应该跟踪在纸上每一个操作是什么,以及占的进程数。不要忘记,fork()的创建当前进程的一个近乎完美的副本。最显著的差异(在大多数情况下)是叉()的返回值父母和孩子之间的区别。 (由于此code忽略返回值,这都没有区别。)

The fork() primitive often stretches the imagination. Until you get a feel for it, you should trace out on paper what each operation is and account for the number of processes. Don't forget that fork() creates a near-perfect copy of the current process. The most significant difference (for most purposes) is that fork()'s return value differs between parent and child. (Since this code ignores the return value, it makes no difference.)

因此​​,在第一,有一个过程。创建一个第二过程,这两个打印一个点和循环。在他们的第二次迭代,每次创建另一个副本,所以有四个过程打印这个点,然后退出。因此,我们可以很容易地占据六个点,像你期望的那样。

So, at first, there is one process. That creates a second process, both of which print a dot and loop. On their second iteration, each creates another copy, so there are four processes print a dot, and then exit. So we can easily account for six dots, like you expect.

然而,的printf()确实是缓冲输出。所以写的时候,从当时只有两个进程的第一个点不会出现。这些点保留在缓冲器MDASH;其在叉()复制。它不是直到进程即将退出时出现的缓冲点。四个过程打印缓冲点,再加上新给出了8点。

However, what printf() really does is buffer its output. So the first dot from when there were only two processes does not appear when written. Those dots remain in the buffer—which is duplicated at fork(). It is not until the process is about to exit that the buffered dot appears. Four processes printing a buffered dot, plus the new one gives 8 dots.

如果你想避免这种行为,呼吁 fflush(标准输出); 的printf()

If you wanted to avoid that behavior, call fflush(stdout); after printf().

这篇关于fork()的分支机构超过预期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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