printf anomaly after “fork()”

前端 未结 3 1043
轻奢々
轻奢々 2020-11-21 04:57

OS: Linux, Language: pure C

I\'m moving forward in learning C programming in general, and C programming under UNIX in a special case.

I detected a strange (f

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 05:47

    The reason why is that without the \n at the end of the format string the value is not immediately printed to the screen. Instead it is buffered within the process. This means it is not actually printed until after the fork operation hence you get it printed twice.

    Adding the \n though forces the buffer to be flushed and outputted to the screen. This happens before the fork and hence is only printed once.

    You can force this to occur by using the fflush method. For example

    printf( "Hello, my pid is %d", getpid() );
    fflush(stdout);
    

提交回复
热议问题