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.
CPP
#include <iostream>
#include <sys/wait.h> // for wait()
#include <unistd.h> // for fork()
int main()
{
pid_t id1 = fork();
pid_t id2 = fork();
if (id1 > 0 && id2 > 0) {
wait(NULL);
wait(NULL);
cout << "Parent Terminated" << endl;
}
else if (id1 == 0 && id2 > 0) {
sleep(2);
wait(NULL);
cout << "1st child Terminated" << endl;
}
else if (id1 > 0 && id2 == 0) {
sleep(1);
cout << "2nd Child Terminated" << endl;
}
else {
cout << "Grand Child Terminated" << endl;
}
return 0;
}
|
Python3
import os
import time
if __name__ = = "__main__" :
pid1 = os.fork()
pid2 = os.fork()
if pid1 > 0 and pid2 > 0 :
os.wait()
os.wait()
print ( "Parent terminated" )
elif pid1 = = 0 and pid2 > 0 :
time.sleep( 2 )
os.wait()
print ( "1st child terminated" )
elif pid1 > 0 and pid2 = = 0 :
time.sleep( 1 )
print ( "2nd child terminated" )
else :
print ( "Grand child terminated" )
|
Output:
Grand Child Terminated
2nd Child Terminated
1st child Terminated
Parent Terminated
Time Complexity: O(1)
Auxiliary Space: O(1)