fork() and “\\n” [duplicate]

2019-01-26 19:24发布

问题:

This question already has an answer here:

  • printf anomaly after “fork()” 3 answers

I just made a simple demo program in C to see how fork() works and came across something that I don't understand. In this example:

void fork2()
{
    printf("A");
    fork();
    printf("B");
}

The output is ABAB, but in this example:

void fork2()
{
    printf("A\n");
    fork();
    printf("B\n");
}

The output is ABB (separate lines of course). The second one makes sense, because if I understand fork() correctly it spawns a new child that starts right after where the fork() took place (so printf("B\n"); in this case). What I don't understand, is why the output is different when I include the new line character.

回答1:

printf() buffers output until a newline is encountered. So your \n-less version stuffs A into the output buffer, forks.

Since both processes are identical (minus PIDs and whatnot), they now both have an output buffer that contains A.

The execution continues and prints B into the buffers in each process. Both processes then exit, causing a flush of the output buffer, which prints AB twice, once for each process.

You other version, having \n, causes that output buffer to flush after the first printf() call, and when the fork hits, both processes have an empty buffer.



回答2:

First of all, do not define a fork() function in your code. fork() is a system call already defined for you.

You call fork() and once it (successfully) returns, you have two identical processes executing the next line of the code past the fork() invocation. In the parent process fork() will return the PID of the child; in the child process the return code is 0. based on this return code, your two processes can do whatever they intended to based on their roles.

Now, there is no guarantee on relative order of execution of these two processes. For all you know, child might not execute for the next 2 minutes and it would still be the correct behavior. So, this means you cannot expect the order of the output from both of those processes to be predictable.

Finally, change printf() to fprintf() to avoid buffering (which confuses things further in this case).



标签: c fork