如果我叫里面主要fork()的,会发生什么? [英] What happens if I call fork() inside main?

查看:96
本文介绍了如果我叫里面主要fork()的,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的一块code的:

Simple piece of code:

#include <stdio.h>
#include <string.h>

main()
{
     printf("Process");
     fork();
     fork();
     return 0;
}

从我的叉子的理解(),在此之后code执行,我们将有3子进程和1父进程。此外,每当我们调用fork()的执行应该从语句中的fork()的语句后立即开始。因此,根据我的过程的应该只打印一次。但是,在我的输出进程正在打印的4倍。这怎么可能?

From my understanding of fork(), after this code executes we will have 3 child processes and 1 parent process. Also whenever we call fork() the execution should start from the statement immediately after the fork() statement. Hence according to me "Process" should be printed only once. But in my output Process is being printed 4 times. How is that possible?

推荐答案

由于标准输出线在默认情况下缓冲,当你调用叉(),输出缓冲器由所有的孩子进程继承。

Because the standard output is line buffered by default, when you call fork(), the output buffer is inherited by all the children processes.

有几种不同的方法来改变这种行为:

There are several different ways to change this behavior:

结尾添加新行字符:

printf("Process\n");

或呼叫 fflush()来刷新输出:

printf("Process");
fflush(stdout);

或更改标准输出使用没有缓冲的 函数setbuf() setvbuf用来()

or change standard output to not buffered using setbuf() or setvbuf():

setbuf(stdout, NULL);
printf("Process");

使用无论哪种方式,你会看到输出只有一次。

Using either way, you'll see the output only once.

注:参见 @Dvaid施瓦茨对错误答案与调用的atexit()在code多次。

Note: see @Dvaid Schwartz's answer for the bug with calling atexit() multiple times in your code.

这篇关于如果我叫里面主要fork()的,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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