Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does the process start to execute after fork()

Tags:

c

fork

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


int main(void) {
    for (int i = 1; i < 4; i++) {
        printf("%d", i);
        int id = fork();
        if (id == 0) {
            printf("Hello\n");
            exit(0);
        } else {
            exit(0);
        }
    }
    return 0;
}

For this code, it prints 11Hello on my computer. It seems counter-intuitive to me because "1" is printed twice but it's before the fork() is called.

like image 754
tyy Avatar asked Nov 06 '22 00:11

tyy


1 Answers

The fork() system call forks a new process and executes the instruction that follows it in each process parallelly. After your child process prints the value of i to the stdout, it gets buffered which then prints the value of 'i' again because stdout was not flushed.

Use the fflush(stdout); so that 'i' gets printed only once per fork.

Alternately, you could also use printf("%d\n", i); where the new line character at the end does the job.

like image 79
Vens8 Avatar answered Nov 15 '22 12:11

Vens8