// Source: https://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/files/signal4.c

/* signal4: parent creates multiple child processes and detects
   their termination via a signal 
   Each child prints an "I'm the child" message and exits after n seconds,
   where n is the sequence in which it was forked. 
   Paul Krzyzanowski */

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

#define NUMPROCS 4	/* number of processes to fork */
int nprocs;		/* number of child processes */

void child(int n) {
	printf("\tChild[%d]: child pid=%d, sleeping for %d seconds\n", n, getpid(), n);
	sleep(n);	
	printf("\tchild[%d]: I'm exiting\n", n);
	exit(100+n); }

void catch(int snum) {
     int pid, status;
     pid = wait(&status);
     printf("Parent process: child process pid=%d exited with value %d\n",
	     pid, WEXITSTATUS(status));
     nprocs--;
     signal(SIGCHLD, catch); }
     
int main(int argc, char **argv) {

	int pid, i;	
	signal(SIGCHLD, catch);
	for (i=0;i<NUMPROCS;i++) {
	        pid=fork();
	        if (pid<0) { perror("fork"); exit(1); }
	        if (pid==0) child(i);
	        else nprocs++; }
	printf("Parent process: going to sleep\n");
	while (nprocs != 0) {
		printf("parent: sleeping\n");
		sleep(60); }
	printf("Parent process: exiting\n");
	exit(0); }


     
