Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Medium

Fork() System Call

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

An operating system (OS) is a software program that serves as a conduit between computer hardware and the user. It is a piece of software that coordinates the execution of application programs, software resources, and computer hardware. It also aids in the control of software and hardware resources such as file managementmemory management, input/output, and a variety of peripheral devices such as a disc drive, printers, and so on.

fork system call

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.

fork() return the following values:

  • Negative value - it represents the creation of the child process was unsuccessful.
  • Zero - it represents a new child process is created.
  • Positive value - The process ID of the child process to the parent. The returned process ID is type pid_t defined in sys/types.h. Usually, the process ID is an integer.

Since the child and parent processes run concurrently, these processes reside in different memory spaces.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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.

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: 

 

Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like AmazonAdobeGoogleUberMicrosoft, etc. on Coding Ninjas Studio.

Topics covered
1.
Introduction
2.
What is the fork () system call?
3.
What is the Use of Fork System Call?
4.
fork() in C language
5.
Syntax for fork() System Call
6.
Examples of fork() statements
6.1.
Example1
6.1.1.
Implementation
6.1.2.
Output
6.2.
Example2
6.2.1.
Implementation
6.2.2.
Output
6.3.
Example3
6.3.1.
Implementation
6.3.2.
Output
7.
Advantages of Fork System Call
8.
Disadvantages of Fork System Call
9.
Frequently Asked Questions
9.1.
What is the fork () system call?
9.2.
What does the fork () command do?
9.3.
When the fork call returns 0?
9.4.
How many times fork () system call return in a single call?
10.
Conclusion