fork()和"\ n" [英] fork() and "\n"
问题描述
我只是在C
中制作了一个简单的演示程序,以了解fork()
的工作原理,并遇到了我不了解的内容.在此示例中:
I just made a simple demo program in C
to see how fork()
works and came across something that I don't understand. In this example:
void fork2()
{
printf("A");
fork();
printf("B");
}
输出为ABAB
,但在此示例中:
The output is ABAB
, but in this example:
void fork2()
{
printf("A\n");
fork();
printf("B\n");
}
输出为ABB
(当然是单独的行).第二个是有道理的,因为如果我正确理解fork()
,它将产生一个新的子代,该子代在fork()
发生的地方之后开始(在本例中为printf("B\n");
).我不明白的是,为什么当我包含换行符时输出会有所不同.
The output is ABB
(separate lines of course). The second one makes sense, because if I understand fork()
correctly it spawns a new child that starts right after where the fork()
took place (so printf("B\n");
in this case). What I don't understand, is why the output is different when I include the new line character.
推荐答案
printf()
缓冲输出,直到遇到换行符为止.因此,您的\n
-less版本会将A
塞入输出缓冲区,分叉.
printf()
buffers output until a newline is encountered. So your \n
-less version stuffs A
into the output buffer, forks.
由于两个进程都是相同的(减PID和诸如此类),所以它们现在都具有包含A
的输出缓冲区.
Since both processes are identical (minus PIDs and whatnot), they now both have an output buffer that contains A
.
执行继续,并在每个进程的缓冲区中打印B
.然后,这两个进程都退出,导致刷新输出缓冲区,该缓冲区两次输出AB
,每个进程一次.
The execution continues and prints B
into the buffers in each process. Both processes then exit, causing a flush of the output buffer, which prints AB
twice, once for each process.
另一个版本为\n
的版本会导致在第一次调用printf()之后刷新输出缓冲区,并且当fork命中时,两个进程都有一个空缓冲区.
You other version, having \n
, causes that output buffer to flush after the first printf() call, and when the fork hits, both processes have an empty buffer.
这篇关于fork()和"\ n"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!