Here's a code where I use 2 fork() system calls one after another - How does it actually work?
#include <unistd.h>
#include <iostream.h>
using namespace std;
int main()
{
cout << "0. I am process " << getpid() << endl;
(void) fork();
cout << "1. I am process " << getpid() << endl;
(void) fork();
cout << "2. I am process " << getpid() << endl;
}
I get the output as :
0. I am process 27701
1. I am process 25915
1. I am process 27701
2. I am process 27781
2. I am process 26170
2. I am process 27701
This is the next program where I've used 3 fork system calls, how do I get such an output? If I were to solve this code manually, what would be the logic?
#include <unistd.h>
#include <iostream>
using namespace std;
int main()
{
cout << "0. I am process " << getpid() << endl;
(void) fork();
cout << "1. I am process " << getpid() << endl;
(void) fork();
cout << "2. I am process " << getpid() << endl;
(void) fork();
cout << "3. I am process " << getpid() << endl;
}
Here I get the output as :
0. I am process 27116
1. I am process 26147
2. I am process 27371
2. I am process 26147
3. I am process 24416
3. I am process 27371
3. I am process 27508
3. I am process 26147
1. I am process 27116
2. I am process 21406
2. I am process 27116
3. I am process 27369
3. I am process 21406
3. I am process 26752
3. I am process 27116