Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C fork program explanation

Tags:

c

fork

stdio

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.

like image 344
jackson Avatar asked Dec 11 '25 04:12

jackson


1 Answers

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.

like image 154
ネロク・ゴ Avatar answered Dec 13 '25 20:12

ネロク・ゴ