Search code examples
cprintfforkparent

C fork is a copy of parent when using printf


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

int main(void) {
    write(STDOUT_FILENO,"1",1);
    if(fork() > 0) {
        write(STDOUT_FILENO,"2",1);
        write(STDOUT_FILENO,"3",1);
    }
    else {
        write(STDOUT_FILENO,"4",1);
        write(STDOUT_FILENO,"5",1);
    }
    write(STDOUT_FILENO,"\n",1);
    return 0;
}

Output is 1 2 3 \n 4 5 \n

Why is that that if I replace all write functions for printf(without newline character in the end) like write(STDOUT_FILENO,"1",1)==printf("1") I get 1 2 3 \n 1 4 5 \n, like the child is copying the line above the fork?


Solution

  • Yes this is because the stdout stream is buffered till it encounters a endline as per this post Why does printf not flush after the call unless a newline is in the format string?. So when you form a new process this buffer is copied to the child's stdout buffer since we are essentially making a new memory space for the child. (Actually not quite, see Specifically, how does fork() handle dynamically allocated memory from malloc() in Linux? )

    This is what will work

    #include <stdio.h>
    #include <sys/types.h>
    #include <unistd.h>
    int main(void) {
    
    printf("1");
    fflush(stdout);
    if(fork() > 0) {
            printf("2");
            printf("3");
    } else {
            printf("4");
            printf("5");
    
    }
    printf("\n");
    return 0;
    }