叉(c)中选择使用printf [英] fork() in c using printf
问题描述
有2个不同的方案,它们体积小,例如:
There are 2 different programs, they are small for example:
int main()
{
printf ("print hello");
fork();
}
int main()
{
printf ("print hello\n");
fork();
}
输出1:`打印helloprint你好
output 1 is: `print helloprint hello
2的输出是:打印你好
现在的问题是,为什么一个与 \\ n
只能打印一次,第一次印刷了两次?
The question is, why does the one with the \n
only print once, and the first one prints it twice?
推荐答案
您正在运行到系统的的printf
执行的缓冲行为。在第一种情况下,该字符串被打印到一个缓冲区,但是因为没有换行(你没叫 fflush
),它只是坐在那里缓冲区。然后你叉,两个分叉缓冲被刷新时,它们各自的进程退出。
You're running into the buffering behaviour of your system's printf
implementation. In the first case, the string is printed to a buffer, but since there's no newline (and you didn't call fflush
), it's just sitting there in that buffer. Then you fork, and both forked buffers are flushed when their respective processes exit.
在第二种情况下, \\ n
会导致刷新缓冲区的前的叉,所以没有剩余时,派生进程输出退出。
In the second case, the \n
causes the buffer to be flushed before the fork, so there's no output remaining when the forked processes exit.
这篇关于叉(c)中选择使用printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!