IO缓冲对fork的影响

Linux下标准输出是行缓冲的,这个特点刚不晓得的人很迷惑,行缓冲居然对fork出来的新进程也有影响这倒是今天头一次见。

得到一份代码如下:

#include <stdio.h>
#include <unistd.h>
int main(void)
{
        printf("one");
        fork();
        printf("two/n");
        return 0;
}


输出结果颇为怪异:

[dave@dave ~]$ gcc test1.c;./a.out
onetwo
onetwo


 

这时想到是不是fork()进程后,把行缓冲也给继承来了。于是修改下代码,用fflush强制把缓冲区刷新。

#include <stdio.h>
#include <unistd.h>
int main(void)
{
        printf("one");
        fflush(stdout);
        fork();
        printf("two/n");
        return 0;
}


于是运行结果变得正常了

[dave@dave ~]$ gcc test1.c;./a.out
onetwo
two


 

想消除行缓冲所带来的困扰,方法如下

1、输出数据后加换行符

2、使用fflush之类的函数强制刷新

3、使用setbuf,setvbuf函数设置缓冲区大小

4、使用非缓冲的的流,如stderr.

This entry was posted in Linux and tagged . Bookmark the permalink.

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注