Understanding C's fork() through a simple example

后端 未结 2 1735
悲&欢浪女
悲&欢浪女 2021-02-02 02:59
#include 
int num = 0;
int main(int argc, char*argv[]){
    int pid;
    pid = fork();
    printf(\"%d\", num);  
    if(pid == 0){       /*child*/
               


        
2条回答
  •  -上瘾入骨i
    2021-02-02 03:17

    This is not the problem with fork(). It is the printf() since printf() is buffered. Normally the buffer is flushed when it encounters a newline character at the end, '\n'. However since you have omitted this, the contents of the buffer stays and is not flushed. In the end, both processes (the original and the child) will have the output buffer with 0 or 1 in it. When it eventually gets flushed, you'll see this in both processes.

    add fflush(stdout); after printf() and try.

提交回复
热议问题