Search code examples
coperating-systempipeforkunnamed-pipes

Child process executing parent code (lines before the fork)


I'm having difficulty understanding the behavior of fork(). I thought the child process will execute the lines "after" the fork(). So I expected to see only one "Hello world!", but this code:

printf("Hello World!\n");
fork();
return 0;

outputs two "Hello World". Why is that?

I also noticed from online examples using pipe() that pipes are created before forking a child. How does the child also have a pipe when it was created after the creation of the pipe in the parent process?


Solution

  • The first question is more than likely related to your program's file buffering mode, it's likely using full buffering setup, meaning that the stream is only written once the buffer (stdout) is full, this will delay the output, and the child process will also output, because it has the same stdout.

    If you use fflush(stdout) right after the printf, or if you change your buffering mode (setvbuf) to line buffered or not buffered at all, you will prevent the duplicate output because it will happen before the fork.

    As for the second question, the child process duplicates the code of the parent process, after the fork, as you correctly mentioned, but it also duplicates the file table. By creating the unnamed pipes before the fork you will assure the child has the same file descriptors. This is commonly used to setup pipe comunication between child and parent processes.

    You can check the /proc/<process id>/fd folder for each one of the two processes to confirm this.

    Footnote

    For future reference, these are two different subjects, albeit tangential, they belong in different questions, you can see one of the problems here, the question was close with duplicates related to the first question but not the second, though by chance it didn't remain unanswered, it's still burried in a different matter and virtually undiscoverable by other users.