हम जानते हैं कि फोर्क () सिस्टम कॉल का उपयोग प्रक्रिया को दो प्रक्रियाओं में विभाजित करने के लिए किया जाता है। यदि फ़ंक्शन कांटा () 0 देता है, तो यह चाइल्ड प्रोसेस है, और अन्यथा यह पैरेंट प्रोसेस है।
इस उदाहरण में हम देखेंगे कि कैसे प्रक्रियाओं को चार बार विभाजित किया जाता है, और उन्हें नीचे से ऊपर की तरह उपयोग किया जाता है। तो सबसे पहले हम दो बार fork() फंक्शन का प्रयोग करेंगे। तो यह एक बाल प्रक्रिया उत्पन्न करेगा, फिर अगले कांटे से यह एक और बच्चा उत्पन्न करेगा। उसके बाद आंतरिक कांटे से यह स्वचालित रूप से उनमें से एक पोता उत्पन्न करेगा।
हम कुछ विलंब उत्पन्न करने के लिए प्रतीक्षा () फ़ंक्शन का उपयोग करेंगे और प्रक्रियाओं को नीचे से ऊपर की तरह निष्पादित करेंगे।
उदाहरण कोड
#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;
} आउटपुट
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:~$