Why does this code print two times? [duplicate]

2019-01-09 17:55发布

Possible Duplicate:
Working of fork() in linux gcc

#include <stdio.h>

void main ()
{
  printf ("ciao");
  fork ();
}

I have some ideas about C optimization but I'm not sure. Hope you know the answer.

2条回答
啃猪蹄的小仙女
2楼-- · 2019-01-09 18:17

when fork() is called, both parent and child process inherit it and therefore they both will

print out "ciao" when they flush the buffer. If you call fflush(stdout);

before calling fork it will print only once

查看更多
ら.Afraid
3楼-- · 2019-01-09 18:24

The code will probably print "ciao" twice as standard output is buffered IO so the internal buffer for standard output will be replicated in the child process and both buffers flushed when each process, the parent and child, exits.

It is unrelated to optimization.

查看更多
登录 后发表回答