Дочерний процесс не генерируется, и программа, кажется, попала в бесконечный цикл - PullRequest
0 голосов
/ 04 мая 2020

Я экспериментирую с разветвлением сигналов, но я не уверен, что происходит с моим кодом. Я должен получить 3 всего процесса. 1 родитель, 1 ребенок и 1 внук. Я уменьшаю переменную уровня на 1 каждый раз, когда делаю разветвление, поэтому программа должна завершиться.

Я не понимаю, почему программа не генерирует дочерние процессы. Когда я делаю PS Aux | grep selfCaller Я вижу только 1 процесс, запускаемый одновременно.

#include    <stdlib.h>
#include    <stdio.h>
#include    <string.h>
#include    <unistd.h>
#include    <signal.h>

const int   TEXT_LEN    = 16;

const int   NUM_SECS_TO_RUN = 30;

#define     PROGNAME    "selfCaller"


int     numTimesCalled[3]
                = {0,0,0};

pid_t       pidToSignal = -1;

pid_t       childPid    = -1;

int     level       = +2;

int     shouldRun   = 1;

void sigAlarmHandler(int sig){

    printf("Process %d: called level 0\n",level);
    int w = rand() % 10 + 1;
    alarm(w);
    numTimesCalled[0]++;
    if(level != 2){
        pid_t pid = getppid();
        kill(SIGUSR1, pid);
    }

}
void sigUs1Handler(int sig){
    printf("Process %d: called level 1\n",level);
    numTimesCalled[1]++;
    if(level != 2){
        pid_t pid = getppid();
        kill(SIGUSR2, pid);
    }

}
void sigUs2Handler(int sig){
    printf("Process %d: called level 2\n",level);
    numTimesCalled[2]++;

}
void sigIntHandler(int sig){
    shouldRun = 0;
}

int     main        (int        argc,
                 char*      argv[]
                )
{
    int comm;
  if (argc > 1){
  comm = strtol(argv[1], NULL, 0);
  }
  if (comm == 0 || comm == 1){
      level = comm;
  }
  srand(getpid());
  struct sigaction act;
  memset(&act, '\0', sizeof(act));


  act.sa_handler = sigAlarmHandler;
  sigaction(SIGALRM, &act, NULL);

  act.sa_handler = sigAlarmHandler;
  sigaction(SIGUSR1, &act, NULL);

  act.sa_handler = sigUs1Handler;
  sigaction(SIGUSR2, &act, NULL);

  act.sa_handler = sigIntHandler;
  sigaction(SIGINT, &act, NULL);
//   alarm(0);

  pid_t pi;
  if(level > 0){
    pi = fork();
  }
  printf("pid is %d", pi);
  if (pi ==-1){
      exit(EXIT_FAILURE);
  }
 char   text[TEXT_LEN];

  if(pi == 0){
      printf("This is the child");
      int r;
    snprintf(text,TEXT_LEN,"%d",level-1);
      r =execl(PROGNAME, text, NULL);
      if (r==-1){
          fprintf(stderr,"Cannot find %s\n",PROGNAME);
           exit(EXIT_FAILURE);
      }
  }

 if  (level == 2)
{
  int       i;

  for  (i = 0;  i < NUM_SECS_TO_RUN;  i++)
  {
    sleep(1);
  }
}
else
{
  pidToSignal   = getppid();

  while  (shouldRun)
  {
    sleep(1);
  }
}





  printf("Level %d: %d %d %d\n",level,
     numTimesCalled[0],numTimesCalled[1],numTimesCalled[2]
    );

  return(EXIT_SUCCESS);  
}
...