Unix fork() system call what runs when?

后端 未结 1 1040
执念已碎
执念已碎 2021-01-05 18:24
void child(int pid){
    printf(\"Child PID:%d\\n\",pid);
    exit(0);    
}
void parent(int pid){
    printf(\"Parent PID:%d\\n\",pid);
    exit(0);
}

void init(){         


        
1条回答
  •  离开以前
    2021-01-05 18:47

    There's only one process until the fork. That is, that path is executed only once. After the fork there are 2 processes so the code following that system call is executed by both processes. What you ignore is that both terminate and both will call exit.

    In your code you're not flushing stdio. So both processes do that (exit flushes stdio buffers) - that's why you're seeing that output.

    Try this:

    printf("pre fork()\n");
                      ^^ should flush stdout
    

    Or maybe

    printf("pre fork()\n");
    fflush(stdout);
    

    0 讨论(0)
提交回复
热议问题