fork() to execute processes from bottom to up using wait() in C++


We know that the fork() system call is used to divide the process into two processes. If the function fork() returns 0, then it is child process, and otherwise it is parent process.

In this example we will see how to split processes four times, and use them in bottom up manner. So at first we will use fork() function two times. So it will generate a child process, then from the next fork it will generate another child. After that from the inner fork it will automatically generates a grandchild of them.

We will use wait() function to generate some delay and execute the processes as bottom up manner.

Example Code

#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
int main() {
   pid_t id1 = fork(); //make 4 process using two consecutive fork. The main process, two children and one grand child
   pid_t id2 = fork();
   if (id1 > 0 && id2 > 0) { //when both ids are non zero, then it is parent process
      wait(NULL);
      wait(NULL);
      cout << "Ending of parent process" << endl;
   }else if (id1 == 0 && id2 > 0) { //When first id is 0, then it is first child
      sleep(2); //wait 2 seconds to execute second child first
      wait(NULL);
      cout << "Ending of First Child" << endl;
   }else if (id1 > 0 && id2 == 0) { //When second id is 0, then it is second child
      sleep(1); //wait 2 seconds
      cout << "Ending of Second child process" << endl;
   }else {
      cout << "Ending of grand child" << endl;
   }
   return 0;
}

Output

soumyadeep@soumyadeep-VirtualBox:~$ ./a.out
Ending of grand child
Ending of Second child process
Ending of First Child
Ending of parent process
soumyadeep@soumyadeep-VirtualBox:~$

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements