What happens if I call fork () inside main?

The simple part of the code is:

#include <stdio.h>
#include <string.h>

main()
{
     printf("Process");
     fork();
     fork();
     return 0;
}

From my understanding of fork (), after executing this code we will have 3 child processes and one parent process. Also, whenever we call fork (), execution should begin with a statement immediately after the fork () statement. Therefore, according to me, “Process” should be printed only once. But in my output, the process is printed 4 times. How is this possible?

+3
source share
2 answers

Since standard output is buffered by default by default, when called, the fork()output buffer is inherited by all child processes.

There are several ways to change this behavior:

:

printf("Process\n");

fflush(), :

printf("Process");
fflush(stdout);

setbuf() setvbuf():

setbuf(stdout, NULL);
printf("Process");

, .

: . @Dvaid Schwartz answer atexit() .

+10

. main, atexit . _exit.

:

#include <stdio.h> 
#include <string.h>
#include <unistd.h>

main()
{
     int is_child = 0; 
     printf("Process");

     if (fork() == 0) 
        is_child = 1; 

     if (fork() == 0) 
        is_child = 1;

     if (is_child)
        _exit(0);

     return 0;
}
+4

All Articles