Search code examples
cforkstdio

C fork program explanation


I have a code as below

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

int main(int argc, char *argv[])
{
    printf("a\n");
    fork();

    printf("b\n");
    if(fork() == 0) {
        printf("c\n");
        exit(0);    
    }
    printf("d\n");
    return 0;
}

Output :

a
b
d
a
b
c
a
b
d
a
b
c

I don't know why the output duplicated many times.


Solution

  • I don't know why the output duplicated many times

    Because printf() is buffered.

    When a process calls fork(), the resulting child process obtains a copy of the parent's output buffer.

    You can empty this output buffer by placing fflush(stdout) just before each call to fork(). In that case output should be:

    a
    b
    b
    d
    c
    d
    c
    

    Note that if the output refered to a terminal, it would be line-buffered by default, i.e.: the buffer would be dumped every time a \n is sent to the output. Not so if you are redirecting the output to a file.