Write a C Program to Create a Child Process Using the System Calls Fork

Aim:

To write a C Program to Create a Child Process Using the System Calls Fork.

Instructions:

System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork():

  • If fork() returns a negative value, the creation of a child process was unsuccessful.
  • fork() returns a zero to the newly created child process.
  • fork() returns a positive value, the process ID of the child process, to the parent. The returned process ID is of type pid_t defined in sys/types.h. Normally, the process ID is an integer. Moreover, a process can use function getpid() to retrieve the process ID assigned to this process.

Exercise:

If p1 and p2 are two processes and p2 is a child of p1. Write a program to implement how the child will fork for a system call.

Algorithm:

  • Step 1 − START.
  • Step 2 – child process using system call-fork
  • Step 3 − print hello.
  • Step 4 − STOP.

Program:

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

Execution:

hello
hello
hello
hello
hello
hello
hello
hello

Result:

 Thus fork system call program was executed Successfully.

Leave a Comment