1

While I was playing around with fork() I noticed a rather strange behavior but I couldn't figure out myself why this happens.

In the example below, each time fork() is invoked the output from the printf() invocation prior to that is printed out to stdout. The value of test in the output shows that printf() does not really get executed again, otherwise this would increase test each time.

Even stranger - or maybe key to the solution - is the fact that this behavior doesn't occur when I add \n to the end of the format string of printf().

Does anybody know why this happens? Maybe it is related to the stdout buffer? I'm not really familiar with this stuff.

Or am I doing something horribly wrong??

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(char* args) {
    pid_t pid;
    int wstatus;
    int test = 0;

    printf("\n[%d] parent start | test = %d ", getpid(), test++);

    // This works fine
    //printf("\n[%d] parent start | test = %d \n", getpid(), test++);

    for(int i = 0; i < 5; i++) {
        if((pid = fork()) == 0) {
            //printf("\n[%d] Child spawned ", getpid());
            exit(0);
        }
        //printf("\n[%d] Printing with fork() commented out works fine", getpid());
    }

    while(wait(&wstatus) > 0);

    printf("\n[%d] parent end\n\n", getpid());
    return 0;
}

Output:

[342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 [342470] parent start | test = 0 
[342470] parent end

In case it's of any use

$ uname -a
Linux Aspire 5.4.0-26-generic #30-Ubuntu SMP Mon Apr 20 16:58:30 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
0
2

The printf has written text to the stdout buffer, which is finally written in each branch of the fork via the exit call.

Not the answer you're looking for? Browse other questions tagged or ask your own question.