Why strange behavior of fork system call? [duplicate]

北城余情 提交于 2019-12-13 07:27:14

问题


int main(void) {
    printf("abc");
    fork();
    return 0;
}

Output of this code is :

abcabc

Why is it printing twice, even when fork system call is after the printf statement?

Ideone link


回答1:


Because stdout is buffered, often line-buffered. And in your program the buffer is flushed only at exit time, or when returning from main (and that happens "twice" when fork don't fail).

Try adding fflush(NULL); before the fork(); (which you should almost always do)

BTW, you should always keep the result of fork and handle three cases: fork failure, in child, in parent.

So fork is behaving as it should, but printf has not the naive immediate side-effect you imagine: it is buffering so the real output may happen latter. You'll also observe the buffering by replacing fork() with sleep(15) (the output happening at exit time, or at end of main, so after the sleep, and for 15 seconds your program won't apparently output anything)

You might also use strace(1) to understanding what system calls are happening...



来源:https://stackoverflow.com/questions/34978568/why-strange-behavior-of-fork-system-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!