What is the Use of Fork System Call?
The fork() system call in Unix-like operating systems (including Linux) is used to create a new process, which becomes a copy of the calling process. Here's an overview of the use and significance of the fork() system call:
- Process Creation: The primary purpose of the fork() system call is to create a new process, often referred to as the child process. After the fork() call, two processes exist: the parent process and the child process. Both processes have identical copies of the memory, file descriptors, and other resources of the parent process at the time of the fork() call.
- Parallel Execution: By creating a child process, the fork() system call enables parallel code execution. Each process (parent and child) runs independently and can perform different tasks simultaneously.
- Process Control: The fork() system call is fundamental for process control in Unix-like operating systems. It allows programs to spawn new processes, which can execute different sections of code or perform different tasks concurrently.
- Multiple Processes: The ability to create multiple processes through fork() facilitates multitasking and multitasking environments. It allows programs to perform several tasks simultaneously, such as handling multiple client connections in a server application or executing multiple computations in parallel.
- Process Hierarchy: In Unix-like operating systems, processes are organized hierarchically. The process that calls fork() becomes the parent process, and the newly created process becomes its child. This hierarchy enables the management and coordination of processes in the system.
fork() in C language
The fork does not take any arguments and returns a process ID (mostly an integer value).
The following header files are included when we use fork() in C.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
- fork() is defined in <unistd.h> header file, so we need to include this header file to use a fork.
- Type pid_t is defined in <sys/types.h> and process ID’s are of pid_t type.
Read more, gzip command in linux
Syntax for fork() System Call
The following is the syntax of the fork() in Linux or Ubuntu
pid_t fork();
In the syntax, pid_t is the return type, and no arguments are passed to fork(). Whenever the child process is successfully created, the Process ID of the child process is returned in the parent process, and value 0 will be returned to the child process itself.
If any error occurs, then -1 is returned to the parent process, and the child process is not created.
NOTE: The following programs do not compile in the windows environment.
Code
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
//main function begins
int main(){
fork();
printf("the process is created using fork() system call\n");
return 0;
}
Output:
the process is created using fork() system call
the process is created using fork() system call
Examples of fork() statements
Example1
Implementation
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
//main function begins
int main(){
fork();
fork();
fork();
printf("this process is created by fork() system call\n");
return 0;
}
Output
this process is created by fork() system call
this process is created by fork() system call
this process is created by fork() system call
this process is created by fork() system call
this process is created by fork() system call
this process is created by fork() system call
this process is created by fork() system call
this process is created by fork() system call
Here, the total number of processes created is 2^3 = 8, and the print statement is executed eight times.
Example2
Implementation
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
//main function begins
int main(){
pid_t p= fork(); //calling of fork system call
if(p==-1)
printf("Error occured while calling fork()");
else if(p==0)
printf("This is the child process");
else
printf("This is the parent process");
return 0;
}
Output
This is the parent process
This is the child process
Here, the integer value is returned in the variable of type pid_t, p contains 0 when a child process is created, and -1 when the creation of child process is unsuccessful, other while p holds any positive value which is for the parent process. The output order may be different as the parent and child run simultaneously, so two outputs are possible.
Example3
Implementation
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
//main function begins
int main(){
pid_t p= fork(); //calling of fork system call
int x=3;
if(p==0)
printf("In the child, the value of x is %d\n", ++x);
else
printf("In the parent, the value of x is %d\n", - - x);
return 0;
}
Output
In the child, the value of x is 4
In the parent, the value of x is 2
Or
In the parent, the value of x is 2
In the child, the value of x is 4
The variable change in one process does not affect two other processes because the data/state of the two processes is different since parent and child run simultaneously, so two outputs are possible.
You can also read about layered structure of operating system, Open Source Operating System.
Advantages of Fork System Call
- Concurrent Execution: Fork creates a new process, enabling concurrent execution of multiple tasks. This is essential for multitasking and parallelism.
- Resource Sharing: Initially, child and parent processes share the same memory and resources, reducing memory overhead and improving efficiency.
- Isolation: Forked processes run independently, providing fault tolerance. Failures in one process typically do not affect others.
- Process Control: The fork system call allows parent and child processes to have separate execution flows, enabling complex program structures and control over processes.
- Interprocess Communication: Fork lays the foundation for interprocess communication, allowing processes to exchange data and coordinate their activities using mechanisms like pipes and sockets.
Disadvantages of Fork System Call
- High Overhead: Forking a new process involves duplicating the parent process, which can consume a significant amount of system resources and time, leading to high overhead.
- Memory Copying: Initially, parent and child processes share memory, but any modification triggers memory copying, resulting in increased memory consumption and complexity.
- Complexity: Managing the parent-child relationship and synchronizing between processes can be complex and error-prone, particularly in multithreaded applications.
- Inefficient for Heavy Processes: In scenarios where many child processes are created and heavily modified, the overhead of copying memory and resources can be inefficient.
- Limited Portability: Fork is not available on all operating systems, making code using fork less portable. Some systems use alternatives like threads or lightweight processes.
How does the fork() Function in C work?
The `fork()` function in C is used to create a new process, which is called a child process, by duplicating the calling process, which is called the parent process. The `fork()` function is included in the `unistd.h` header file.
Let's discuss how the `fork()` function works in step by step manner:
1. When a process calls the `fork()` function, it creates a new child process that is an exact copy of the parent process, including the same code, data, and stack.
2. After the `fork()` function is called, both the parent and child processes continue executing from the next statement following the `fork()` function.
3. The `fork()` function returns a different value in the parent and child processes:
- In the parent process, `fork()` returns the process ID (PID) of the newly created child process.
- In the child process, `fork()` returns 0.
4. By checking the return value of `fork()`, the program can determine whether it is executing in the parent process or the child process and perform different actions accordingly.
For example :
C
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid;
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid == 0) {
printf("Child process: I am the child!\n");
printf("Child process: My PID is %d\n", getpid());
printf("Child process: My parent's PID is %d\n", getppid());
} else {
printf("Parent process: I am the parent!\n");
printf("Parent process: My PID is %d\n", getpid());
printf("Parent process: My child's PID is %d\n", pid);
}
return 0;
}

You can also try this code with Online C Compiler
Run Code
Output:
Parent process: I am the parent!
Parent process: My PID is 1234
Parent process: My child's PID is 5678
Child process: I am the child!
Child process: My PID is 5678
Child process: My parent's PID is 1234
In this example:
1. The `fork()` function is called, and it creates a new child process.
2. The return value of `fork()` is stored in the `pid` variable.
3. The program checks the value of `pid` to determine whether it is executing in the parent process or the child process.
4. If `pid` is less than 0, it means the `fork()` function failed, and an error message is printed.
5. If `pid` is equal to 0, it means the program is executing in the child process. The child process prints a message indicating that it is the child, along with its own PID (`getpid()`) and its parent's PID (`getppid()`).
6. If `pid` is greater than 0, it means the program is executing in the parent process. The parent process prints a message indicating that it is the parent, along with its own PID (`getpid()`) and its child's PID (`pid`).
Note: Both the parent and child processes continue executing independently from the point after the `fork()` function call. They have separate memory spaces and can perform different tasks or communicate with each other if needed.
Frequently Asked Questions
What is the fork () system call?
The fork() system call is used in Unix-based OS to create a new process by duplicating the calling process. The new process is an exact copy of the parent process, with its own address space and memory.
What does the fork () command do?
The fork() command is a system call in Unix-based OS that creates a new process by duplicating the calling process. The new process is an exact copy of the parent process, with its own address space and memory.
When the fork call returns 0?
When the fork system call returns 0, it signifies that the current process is the child process. This allows the child to execute a different code path from the parent.
How many times fork () system call return in a single call?
The fork() system call returns twice - once in the parent process and once in the newly created child process - in a single call. The parent process receives the child process ID, and child process receives a return value of 0.
Conclusion
In this blog, we learned about the fork() system call; we learned the values returned by fork() and what those values represent. Then we study the syntax of fork() in C language with different examples, which helps us understand how fork() works and processes are created.
Recommended Readings: