#include <iostream>
using namespace std;

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

/* pid_t fork(void) is declared in unistd.h */
/* pid_t is a special type for process ids.  it's equivalent to int. */

int main(void) { 
	pid_t child_pid;     /* i.e., int  pid; */
	int status;
	pid_t wait_result;

	child_pid = fork();
	if (child_pid == 0) 
	{ 
		/* this code is only executed in the child process */ 
		cout << "I am a child and my pid = " << getpid() << endl;
		cout << "My parent is " << getppid() << endl;
		/* an exit here would stop only the child process */
	}
	else if (child_pid > 0) 
	{
		/* this code is only executed in the parent process */
		cout << "I am the parent and my pid = " << getpid() << endl;
		cout << "My child has pid = " << child_pid << endl;
	}
	else 
	{
		cout 	<< "The fork system call failed to create a new process"
			<< endl;
		exit(1);
	}

	/* this code is executed by both parent and child processes */
	cout 	<< "I am a happy, healthy process and my pid = " 
		<< getpid() << endl;

	if (child_pid == 0) 
	{
		/* this code is only executed by the child process */
		cout << "I am a child and I am quitting work now!" << endl;
	}
	else 
	{
		/* this code is only executed by the parent process */
		cout 	<< "I am a parent and I am going to wait for my child" 
			<< endl;
		do 
		{
			/* parent waits for the SIGCHLD signal sent
			   to the parent of a (child) process when 
			   the child process terminates */
			wait_result = wait(&status);
		} while (wait_result != child_pid);
		cout << "I am a parent and I am quitting." << endl;
	}

	return 0;
}

