fork in c lang
  1. fork()” is used in Unix-like operating systems to create a new process. The   is called the “parent” process, and the new process created is called the “child” process.
  2. After a successful fork(), two processes are running the same code: the parent and the child.
  3. The fork() function returns a value that helps to identify whether the code is running in the parent or the child process.

Below are different values returned by fork().

  • Negative Value: The creation of a child process was unsuccessful.
  • Zero: Returned to the newly created child process.
  • Positive value: Returned to parent or caller. The value contains the process ID of the newly created child process.

Table of Content

Table of Contents

Fork() Method in C

Basic Example of fork()

				
					
#include <stdio.h>
#include <unistd.h>
int main() {

    printf("L0\n"); // Print "L0"
    fork();         // Create a new process
    printf("L1\n"); // Print "L1"
    fork();         // Create another new process
    printf("Bye\n"); // Print "Bye"
    
    return 0; 
    }
				
			

Explanation: 

  • printf("L0\n");: The program starts by printing L0 to the screen. This happens only once.

  • fork();: The first fork() is called. This creates a new process. Now, there are two processes:

    • The original parent process.
    • The new child process created by fork().

    Both the parent and the child process will continue to execute the code after the fork().

  • printf("L1\n");: Both the parent and child processes print L1. So, L1 is printed twice.

  • fork();: The second fork() is called. This creates another new process from each of the two existing processes (the parent and the first child). Now, there are four processes in total:

    • The original parent process.
    • The first child process.
    • Two new processes created by the second fork().
  • printf("Bye\n");: All four processes print Bye. So, Bye is printed four times.

Creating a New Process Using fork()

How Many Times Will The Below Code Prints Out?

				
					#include <stdio.h> 
#include <sys/types.h> 
#include <unistd.h> 
int main() 
{ 
	fork(); 
	fork(); 
	fork(); 
	printf("hello\n"); 
	
	return 0; 
}
				
			

The number of times “hello” is printed equals the number of processes created. The total number of processes is 2n, where is the number of fork() system calls.
So, if n=3, the total is 23 = 8 processes.

Printing Process ID For Parent and Child Processes

Example 1: 

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

int main() {
    pid_t pid = fork();

    if (pid < 0) {
        printf("Fork failed\n");
        return 1;
    } else if (pid == 0) {
        printf("Child process, PID: %d\n", getpid());
    } else {
        printf("Parent process, PID: %d\n", getpid());
    }
    return 0;
}
				
			

When fork() is called, it creates two processes: the parent and the child. Both processes will run the entire code from that point onward. The getpid() function retrieves the current process’s ID, so it will print the process ID for both the parent and the child.

Example 2: 

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

void forkexample() 
{ 
	int x = 1; 
	pid_t p = fork(); 
	if(p<0){ 
	perror("fork fail");  //(used for printing error msgs)
	exit(1); 
	} 
	else if (p == 0) 
		printf("Child has x = %d\n", ++x); 
	else
		printf("Parent has x = %d\n", --x); 
} 
int main() 
{ 
	forkexample(); 
	return 0; 
} 

				
			

Explanation: 

  • A variable x is initialized to 1.
  • The fork() call creates two processes: the parent and the child.
    • The child process increments x and prints its value.
    • The parent process decrements x and prints its value.

As a result, the output shows how the value of x differs in the parent and child processes due to the separate memory spaces they occupy. The child will print x = 2, while the parent will print x = 0.

  • exit(0): Indicates success.
  • exit(1) or exit(2), etc.: Indicates failure, with different values sometimes used to represent different types of errors.

Creating Multiple Child Processes

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

int main() {
    for (int i = 0; i < 3; i++) {
        if (fork() == 0) {
            printf("Child Process: %d, Parent Process: %d\n", getpid(), getppid());
            return 0;
        }
    }
    for (int i = 0; i < 3; i++) {
        wait(NULL); // Waiting for child processes to finish
    }
    return 0;
}

				
			

Explanation: 

  • Each process is independent after fork(): Once a child process is created, it runs independently of the parent. return 0; in the child process only exits that child, not the parent or any other child processes.
  • The parent process continues to the next iteration of the loop regardless of what happens in the child process.
  • Parent Process:
    • The parent calls fork().
    • fork() creates a child process.
    • In the parent process, fork() returns a positive number (the PID of the child), so the if (fork() == 0) condition is false.
    • The parent process does not enter the if block and continues to the next iteration of the loop.
  • Child Process:
    • In the child process, fork() returns 0, so the if (fork() == 0) condition is true.
    • The child process executes the code inside the if block, prints its message, and then hits return 0;.
    • return 0; causes the child process to exit, but this does not affect the parent process, which continues running
  • The parent process creates another child (Child 2) with fork().
  • The parent again does not enter the if block and moves to the next iteration.
  • The second child process prints its message and exits with return 0;.
  • The parent creates the third child (Child 3) with fork().
  • The parent finishes the loop after this iteration.
  • The third child process prints its message and exits with return 0;.