/*********************************************************
*
* Module Name:  Unix fork example
*
* File Name:    mainProgram.c
*
* Summary:
*  This file shows how to create a worker process.
*
* Revisions:
*
*********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>

void sig_chld(int signo);
void CNTCCode();
void CatchAlarm(int ignored);

int currentNumberOfClients  = 0;

int main(int argc, char *argv[])
{
pid_t childpid;
int loopCount = 2;
int innerLoopCount = 3;
int myVariableA = 1;
static int myVariableB = 1;
struct sigaction myaction;

  signal(SIGCHLD,sig_chld);
  signal (SIGINT,CNTCCode);

  myaction.sa_handler = CatchAlarm;
  if (sigfillset(&myaction.sa_mask) < 0)
       exit(1);     

  myaction.sa_flags = 0;

  if (sigaction(SIGALRM, &myaction, 0) < 0)
       exit(1);     

  alarm(1);
//  while (1) {
    while (loopCount-- > 0) {
      printf("parent(%d): myVariableA = %d\n",(int) getpid(),myVariableA++);
      printf("parent(%d): myVariableB = %d\n",(int) getpid(),myVariableB++);
      currentNumberOfClients++;
      if ( (childpid = fork()) == 0) {      /* child process */
      //Loop a number of times printing the pid and time
        while (innerLoopCount-- > 0) {
          alarm(1);
          printf("child(%d): myVariableA = %d\n",(int) getpid(),myVariableA++);
          printf("child(%d): myVariableB = %d\n",(int) getpid(),myVariableB++);
          sleep(10);
        }
        exit(0);     
      }  //end child
      else {  //parent
       alarm(0);
       sleep(10);
      }

    }
  printf("pid %d is leaving...",(int) getpid());
//  }
  return 0;
}

void CNTCCode() {
  printf("mainProgram:  CNT-C Interrupt,  exiting....\n");
}

void CatchAlarm(int ignored) {
  printf("CatchAlaram (alarm:%d)....my pid:%d\n",ignored,getpid());
}


