How to use a fork() system call

A fork() system call creates a new process which is called the child process. The process that creates the child process is the parent process.

To use the fork() system call, the program needs to include the unistd.h and sys/types.h header files:

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

Explanation

After the creation of the child process, both the parent and the child process start execution from the next instruction after the fork() command. Both processes run concurrently.

When a child process is created, the contents of the memory of the parent process are copied to the memory allocated to the child process.

Parameters and return value

The fork() system call takes no argument and returns an integer value which can be any of the following:

  • -1: The value returned to the parent that indicates the creation of the child process was unsuccessful.
  • 0: The value returned to the child process.
  • Process id of the child process: The value returned to the parent that indicates the creation of the child process was successful.

Example

The following example demonstrates how to use the fork() system call in C.

  • The below program creates a variable of type pid_t for storing the return value of the fork() system call.
  • The child and parent processes execute the appropriate conditional blocks depending on the value returned to them by the fork() call.
  • The parent executes the if else block and the child executes the if block.
  • Both processes obtain their process ids through the getpid() function and display them.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
//create child process
pid = fork();
if (pid == 0)
{
//inside child process
printf("I am the child process\n");
pid_t pidchild;
//get process id
pidchild = getpid();
printf("My id is %d\n", pidchild);
}
else if (pid > 0)
{
//inside parent process
printf("I am the parent process\n");
pid_t pidpar;
pidpar = getpid();
printf("My id is %d\n", pidpar);
}
return 0;
}
Copyright ©2024 Educative, Inc. All rights reserved