在Linux fork()的行为 [英] fork() behavior in linux
问题描述
我是想了解叉,并用C尝试以下操作:
#包括LT&;&stdio.h中GT;
#包括LT&;&unistd.h中GT;无效forker()
{
的printf(%d个:A \\ N,(INT)GETPID());
叉子();
等待();
的printf(%d个:乙\\ n,(INT)GETPID());
的printf(%d个:C \\ n,(INT)GETPID());
叉子();
等待();
的printf(%D:D \\ n,(INT)GETPID());
}INT主要(无效)
{
forker();
返回0;
}
当我编译和运行产生a.out的,这里是我观察到的:
> ./a.out
3560:一个
3561:乙
3561:C
3562:D
3561:D
3560:乙
3560:C
3563:D
3560:D
然而,当我做到以下几点:
> ./a.out> t.txt
奇怪的事情发生了:
>猫t.txt
3564:一个
3565:乙
3565:C
3566:D
3564:一个
3565:乙
3565:C
3565:D
3564:一个
3564:乙
3564:C
3567:D
3564:一个
3564:乙
3564:C
3564:D
有人可以解释这种现象?为什么当它被重定向到一个文件是输出不同的?
我使用Ubuntu 10.10,gcc版本4.4.5。
发生这种情况的原因是数据缓冲。在)叉(的时间,在定向到文件的情况下,你的输出还没有被刷新尚未...所以无论是家长和孩子现在有出色的输出缓冲器。
将调用 fflush(标准输出);
之前每个叉();
来解决这个。 p>
I was trying to understand forks, and tried following in C:
#include<stdio.h>
#include <unistd.h>
void forker()
{
printf("%d: A\n",(int)getpid());
fork();
wait();
printf("%d: B\n",(int)getpid());
printf("%d: C\n",(int)getpid());
fork();
wait();
printf("%d: D\n",(int)getpid());
}
int main(void)
{
forker();
return 0;
}
When I compiled and ran resultant a.out, here is what I observed:
> ./a.out
3560: A
3561: B
3561: C
3562: D
3561: D
3560: B
3560: C
3563: D
3560: D
However when I do the following:
> ./a.out > t.txt
something weird happens:
> cat t.txt
3564: A
3565: B
3565: C
3566: D
3564: A
3565: B
3565: C
3565: D
3564: A
3564: B
3564: C
3567: D
3564: A
3564: B
3564: C
3564: D
Can someone please explain this behavior? Why is the output different when it is redirected to a file?
I am using Ubuntu 10.10, gcc version 4.4.5.
The reason this happens is data buffering. At the time of the fork(), in the case of directing to a file, your output has not been flushed yet... so both the parent and the child now have outstanding output buffers.
Put a call to fflush(stdout);
before each fork();
to resolve this.
这篇关于在Linux fork()的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!