子进程未生成,程序似乎陷入了无限循环

时间:2020-05-04 03:22:03

标签: c process fork

我正在尝试信号分叉,但是我不确定我的代码是怎么回事。 我应该总共获得3个流程。 1个父母,1个孩子和1个孙子。每次创建fork时,都会将level变量减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);  
}

0 个答案:

没有答案
相关问题