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

int main()
{
	int p_pid, pid, ret_value, i, status;
	pid_t w;
	char something[30];
	int sl_vals[5];
	int ind, t,j;
	
	/* 
	 * We want to store the parent pid so we won't kill it
	 * also we want to specify the wait call executioner
	 */
	p_pid=getpid();
	sprintf(something, "PID: %d generating children\n", p_pid);
	write(1, something, strlen(something)+1);
	srand((unsigned) pid=getpid());

	/*
	 * Create 5(several ;-> ) children
	 */
	for(i=0; i<5; ++i)
	{
		/* 
		 * If this is a child then:
		 * set group id as something different than the parent
		 * so that this would not be a hara-kiri later on
		 * Also we want to put them to sleep for a random time and 
		 * increase this time so that a child won't be able to wake up 
		 * before parent gets to the wait call.
		 */
		if ((ret_value=fork()) == 0)	
		{
			 setpgid(0, (unsigned)p_pid+1);
			 sleep((rand()%5)+10+i);
			 
		}
	}
	
	/* 
	 * Parent code: 
	 */
	
	if(getpid() == p_pid)
	{
	
		/*
		 * Wait till first dies and kill the rest with SIGTERM
		 */
		if((w=wait(&status))!=-1)
		{
			printf("TERM was trigegred by: %d, stat returned: %04X \n", w, status);
			kill(-(p_pid+1), SIGTERM);
		}

		/*
		 * Some very basic but necessary error check here :-)
		 */
		else 
		{
			perror("God knows what happened");
			exit(1);
		}
		
		/* 
		 * Wait on the rest of processes to verify the ret value
		 * to prove the SIGTERM
		 */	
		while ((w=wait(&status)) != -1)
		{	 
			 printf("wait on: %d, stat returned: %04X \n", w, status);
		}

		/* 
	 	* Notify of parent termination
	 	*/
		printf("parent terminates\n");
		exit(0);
	}
	/* 
	 * Default exit signal for children is 0x0a in high byte
	 */
	exit(10);
}
/*
adimitro@alef:/student/adimitro/cwork/ch4> ./a.out
PID: 6565 generating children
TERM was trigegred by: 6567, stat returned: 0A00
wait on: 6570, stat returned: 000F
wait on: 6568, stat returned: 000F
wait on: 6566, stat returned: 000F
wait on: 6569, stat returned: 000F
parent terminates
[Logged in :There are 2 users on the server.]
adimitro@alef:/student/adimitro/cwork/ch4>
*/
