I am trying to send a signal to the child processes from a terminal but every time i send a signal to SIGUSR1 or SIGUSR2 it kills the processes. For example when I type "r1" it should refuel the first submarine, but instead it refuels all the submarines, and kills the processes. output says " program terminated by signal SIGUSR2 (User defined signal 2)".

I have already tried sleeping in between the signals.

These are my two functions that I believe the problem is residing in.

void doChild(int SubNum, int Terminal)
{
  Sub = SubNum;
  char string[15];
  sprintf(string, "/dev/pts/%d", Terminal);
  fpt = fopen(string,"w");
  ChildPID[SubNum-1] = getpid();
  srand(time(0)*SubNum);
  Fuel = rand() % 4001 + 1000;
  Missiles = rand() % 5 + 6;
  signal(SIGALRM, AlarmHandler);
  alarm(3);
  signal(SIGUSR1, LaunchMissile);
  signal(SIGUSR2, Refuel);
  while(1);
}

void Input(void)
{
  char inchars[5];


  while (Processes > 0)
  {
    scanf("%s", inchars);
    fflush(stdin);
    numProcess = atoi(&inchars[1]);

    if (strlen(inchars) == 1)
    {
      if (inchars[0] == 'q')
      {
        kill(ChildPID[0], SIGKILL);
        kill(ChildPID[1], SIGKILL);
        kill(ChildPID[2], SIGKILL);
        Processes = 0;
      }
    }

    if (strlen(inchars) == 2)
    {
      if (inchars[0] == 'l')
      {
        kill(ChildPID[numProcess], SIGUSR1);
        break;
      }
      else if (inchars[0] == 'r')
      {
        kill(ChildPID[numProcess], SIGUSR2);
        break;
      }
      else if (inchars[0] == 's')
      {
  //      kill(ChildPID[numProcess], SIGKILL);
        fprintf(fpt, "Sub %d Process Killed", Sub);
        Processes--;
      }
      else printf("Invalid Submarine Number\n");
    }

    if (strlen(inchars) > 2)
    {
      kill(ChildPID[0], SIGKILL);
      kill(ChildPID[1], SIGKILL);
      kill(ChildPID[2], SIGKILL);
      Processes = 0;
      printf("Invalid Input. Processes Killed\n");
    }
  }
}

0 Answers