fork() method explanation with example in C

fork() method in C:

fork is a system call in C. This method creates one child process. The newly created process is called child process and the current process where fork is called is called parent process.

A child process takes same program counter, same files and CPU as the parent process.

This method doesn’t take any parameter, but it returns one integer value. It can be a positive value, negative value or zero.

  • If the return value is negative, it means that the child process creation is failed.
  • If the return value is positive, it means that the child process is created and this is the parent process.
  • If the return value is zero, it means that the child process is created and this is the child process.

Based on the return value of fork(), we can say if it is the child or parent process.

Example of fork:

Let’s take a look at the below example:

#include <stdio.h>

int main() {
    printf("fork() is called and its return value: %d\n",fork());
    printf("Hello world !!\n");
    
    return 0;
}

If you run this program, it will print one output as like below:

fork() is called and its return value: 1563
Hello world !!
fork() is called and its return value: 0
Hello world !!

You can see here that the same strings are printed two times. This is because these are printed once for the parent process and again for the child process.

The difference is the return value of fork() in both processes. The child process prints 0 and the parent process prints 1563.

Example with multiple fork:

Let’s take a look at the below example:

#include <stdio.h>

int main() {
    fork();
    fork();
    fork();
    printf("Hello world !!\n");
    
    return 0;
}

If you run it, it will create total 2^n processes, i.e. 2^3 processes. Each process will print the Hello world !! message.

Hello world !!
Hello world !!
Hello world !!
Hello world !!
Hello world !!
Hello world !!
Hello world !!
Hello world !!