fork() to execute processes from bottom to up using wait()

fork() system call is used to create a process generally known as child process and the process that created it is known as parent process. Now, all the processes that are created using fork() runs concurrently. But what if we want the last process created to execute first and in this manner bottom to up execution such that parent process executes last.

This can be done by using wait() system call. The parent process may then issue a wait() system call, which suspends the execution of the parent process while the child executes and when the child finishes execution, it returns exit status to operating system. Now wait() suspend the process until any of its child process finish execution.

NOTE: This is a linux system call, so it must be executed on linux or unix variant system.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program to demonstrate bottom to up execution
// of processes using fork() and wait()
#include <iostream>
#include <sys/wait.h> // for wait()
#include <unistd.h> // for fork()
int main()
{
    // creating 4 process using 2 fork calls
    // 1 parent : 2 child : 1 grand-child
    pid_t id1 = fork();
    pid_t id2 = fork();
  
    // parent process
    if (id1 > 0 && id2 > 0) {
        wait(NULL);
        wait(NULL);
        cout << "Parent Terminated" << endl;
    }
  
    // 1st child
    else if (id1 == 0 && id2 > 0) {
  
        // sleep the process for 2 seconds
        // to ensure 2nd child executes first
        sleep(2);
        wait(NULL);
        cout << "1st child Terminated" << endl;
    }
  
    // second child
    else if (id1 > 0 && id2 == 0) {
        // sleep the process for 1 second
        sleep(1);
        cout << "2nd Child Terminated" << endl;
    }
  
    // grand child
    else {
        cout << "Grand Child Terminated" << endl;
    }
  
    return 0;
}

chevron_right


Output:

Grand Child Terminated
2nd Child Terminated
1st child Terminated
Parent Terminated


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.