[Solved] Running 3 child processes


Here’s a better instrumented version of your code; it includes the PID in the output, and the outputs are one line each.

#include <iostream>
#include <cstdlib>
#include <sys/wait.h>
#include <unistd.h>

using namespace std;

int main()
{
    int ch1 = fork();
    int ch2 = fork();
    int ch3 = fork();

    if (ch1 == 0) // child1
    {
        cout << (int)getpid() << ": This is child 1 - Finished\n";
        exit(0);
    }
    else if (ch2 == 0)
    {
        waitpid(ch1, 0, 0);
        cout << (int)getpid() << ": This is child 2 - Finished\n";
        exit(0);
    }
    else if (ch3 == 0)
    {
        waitpid(ch2, 0, 0);
        cout << (int)getpid() << ": This is child 3 - Finished!\n";
        exit(0);
    }
    else
    {
        waitpid(ch3, 0, 0);
        cout << (int)getpid() << ": This is parent - waited for all children to finish!\n";
        exit(0);
    }
    return 0;
}

Sample output:

$ ./3kids
40287: This is child 3 - Finished!
40285: This is child 1 - Finished
40286: This is child 2 - Finished
40290: This is child 1 - Finished
40289: This is child 2 - Finished
40288: This is child 1 - Finished
40284: This is parent - waited for all children to finish!
40291: This is child 1 - Finished
$

As you can see, there is one process that considers itself to be child 3, two processes that consider themselves to be child 2, and four processes that consider themselves to be child 1 and one that considers itself to be the parent. This is consistent with the unconstrained forking which creates 8 processes.

To have 3 children only, and to wait for each in turn, you need code more like:

#include <iostream>
#include <cstdlib>
#include <sys/wait.h>
#include <unistd.h>

using namespace std;

void child(int n)
{
    flush(cout);        // No pending output
    int pid = fork();
    if (pid < 0)
        cerr << (int)getpid() << ": failed to fork\n";
    else if (pid == 0)
    {
        cout << (int)getpid() << ": This is child " << n << " - Finished\n";
        exit(0);
    }
    else
    {
        int corpse;
        int status;
        while ((corpse = wait(&status)) != -1)
            cout << (int)getpid() << ": PID " << corpse << " exited with status "
                 << status << "\n";
    }
}

int main()
{
    child(1);
    child(2);
    child(3);
    cout << (int)getpid() << ": This is parent - waited for all children to finish!\n";
    return 0;
}

Sample output:

$ ./3kids
40336: This is child 1 - Finished
40335: PID 40336 exited with status 0
40337: This is child 2 - Finished
40335: PID 40337 exited with status 0
40338: This is child 3 - Finished
40335: PID 40338 exited with status 0
40335: This is parent - waited for all children to finish!
$

3

solved Running 3 child processes