#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <assert.h>

#include <iostream>
using namespace std;

int 
main()
{
    pid_t parent_pid = getpid();
    cout << "starting main(), parent pid = " << parent_pid << endl;

    pid_t child_pid = fork();

    if (child_pid < 0)
    {
        cerr << "fork() failed" << endl;
        exit(1);
    }

    else if (child_pid == 0)
    {
        for (int i = 0; i < 10; i++)
        {
            cout << "hello from the child" << endl;
            sleep(2);
        }
        cout << "child about to call exit(0)" << endl;
        exit(0);
    }

    else
    {
        assert(child_pid > 0);
        for (int i = 0; i < 5; i++)
        {
            cout << "hello from the parent: parent pid = " << parent_pid 
                 << ", child pid = " << child_pid << endl;
            sleep(1);
        }
        cout << "parent waiting for child to finish" << endl;
        assert(wait(NULL) == child_pid); // make sure wait() did error
        cout << "parent after child finished" << endl;
        exit(0);
    }
}

