叉的理解用C [英] Understanding of Fork in C
问题描述
我有一个问题,叉子,我不undertsand。
I have one problem with fork that i don't undertsand.
#include <stdio.h>
#include <string.h>
main(){
printf("test 1.\n");
fork();
printf("test 2.\n");
}
的输出是:
1,测试结果
2.测试结果
1.测试结果
测试2。
test 1.
test 2.
test 1.
test 2.
我不应该越来越...:结果
test1的结果
TEST2结果
测试2
Shouldn't i be getting... :
test1
test2
test2
我真的不明白这一点,因为叉应叉后创建子进程();而不是重新打印teste1。
I really don't understand this because fork should create child process after the fork(); and not printing the teste1 again .
推荐答案
当你调用的printf
,它不会立即打印任何文本。相反,它会等待,直到你打印出大量的文字,或者你叫 fflush(标准输出)
,或退出程序。 (编辑:也有将导致要被打印缓冲文本其他东西)
When you call printf
, it doesn't print any text immediately. Instead it waits until you've printed a lot of text, or you call fflush(stdout)
, or the program exits. ( There are also other things that will cause buffered text to be printed)
在这个过程叉,未印刷文字的份缓冲区(其中包含测试1 \\ n)。这两个过程,然后打印测试1 \\ n,当他们退出。
When the process forks, it copies the buffer of un-printed text (which contains "test 1.\n"). Both processes then print "test 1.\n" when they exit.
调用 fflush(标准输出)
在叉()
修正这一问题,通过确保测试1 \\ n 在这个过程叉子以前实际打印。
Calling fflush(stdout)
before fork()
fixes this, by making sure "test 1.\n" is actually printed before the process forks.
这篇关于叉的理解用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!