/*
 * Exercise 3-9
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <strings.h>


int main()
{
	int i, pid, c_pid, val_ret, pid_ret;
	char *text;

	/*
	 * Create some new processes. We make sure that 
	 * children wil not fork by simply killing themselves
	 * before the next for run.
	 */
	for(i=0; i<3; i++)
	{
		
		if((pid=fork()) == 0)
			kill(getpid(), 9);
	}

	/*
	 * Give them some time to finish up before 
	 * parent code begins.
	 */
	sleep(5);

	/*
	 * And now just perform the waited wait:-)
	 */	
	while((pid_ret=wait(&val_ret)) && pid_ret!=-1)
	{
		printf("child %d terminated and returned %04X\n", pid_ret, val_ret);
	}
	return(0);
}

/*

OUTPUT:
=======

adimitro@alef:/student/adimitro/cwork/ch3> ./a.out& ps -al
[1] 17234
 F S   UID   PID  PPID  C PRI NI     ADDR     SZ    WCHAN TTY      TIME CMD
 8 Z  1040 17236 17234  0   0                                      0:00 <defunct>
 8 S  1015 14238 14236  0  53 20        ?    299        ? pts/2    0:00 bash
 8 S  1040 17232 16996  0  41 20        ?    184        ? pts/4    0:00 pico
 8 S  1015 14251 14238  0  41 20        ?   1059        ? pts/2    0:00 dtsessio
 8 O     0 17235 17095  0  51 20        ?    236          pts/5    0:00 ps
 8 S  1015 14248     1  0  41 20        ?    584        ? pts/2    0:00 ttsessio
 8 S  1040 17234 17095  0  71 20        ?    113        ? pts/5    0:00 a.out
 8 Z  1040 17237 17234  0   0                                      0:00 <defunct>
 8 Z  1040 17238 17234  0   0                                      0:00 <defunct>
adimitro@alef:/student/adimitro/cwork/ch3>
adimitro@alef:/student/adimitro/cwork/ch3> child 17238 terminated and returned 0009
child 17237 terminated and returned 0009
child 17236 terminated and returned 0009

[1]+  Done                    ./a.out
adimitro@alef:/student/adimitro/cwork/ch3> ps -al
 F S   UID   PID  PPID  C PRI NI     ADDR     SZ    WCHAN TTY      TIME CMD
 8 S  1015 14238 14236  0  53 20        ?    299        ? pts/2    0:00 bash
 8 S  1040 17232 16996  0  41 20        ?    184        ? pts/4    0:00 pico
 8 S  1015 14251 14238  0  41 20        ?   1059        ? pts/2    0:00 dtsessio
 8 S  1015 14248     1  0  41 20        ?    584        ? pts/2    0:00 ttsessio
 8 O     0 17252 17095  0  41 20        ?    236          pts/5    0:00 ps
adimitro@alef:/student/adimitro/cwork/ch3>

As we can see there are 3 zombies that belong to 1040(my UID) and then after parent completes
then the children get killed too. attempt to kill them manually will be fruitless.

*/
