#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;
		execl("/bin/ls", "ls", "-l", "fork.html",  NULL);
		/* if execl succeeds, this code is never used */
		cout << "Could not execl file /bin/ls" << endl;
		exit(1);
		/* this exit stops 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 only the parent process because
	   the child either is executing from "/bin/ls" or exited.  */
	cout 	<< "I am a happy, healthy process and my pid = " 
		<< getpid() << endl;


	if (child_pid == 0) 
	{
		/* this code will never be executed */
		printf("This code will never be executed!\n");
	}
	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;
}

