1

次のアイデアを実現するプログラムを書いてみます: 開始後、fork() を使用するプログラム: 子プロセスは prctl(PR_SET_PDEATHSIG, SIGHUP) を使用し、シグナル ハンドラをセットアップします (親の死を検出するのに役立ちます)。プロセスが終了した後、プログラムは再び fork() を使用します。

void forking_process() {
  pid_t id;
  printf("forking_process is called!\n");
  if (id = fork())  {       
          parent_process_operation(); 
       } else {  
          child_process_operation();  
       }
}

void parent_process_operation() {
  int status = 0;
  printf("It's parent process! Pid = %d\n", (int)getpid());
  pid_t chid = wait(&status);
  printf("Terminated child process with PID = %d\n", chid);
  inform_about_parent_death(status);    
}

void child_process_operation() {
  printf("It's child process! pid = %d, ppid = %d\n", 
         (int)getpid(), (int)getppid());
  struct sigaction sa;
  memset(&sa, 0, sizeof(sa));
  sa.sa_handler = inform_about_parent_death;
  if (sigaction(SIGHUP, &sa, NULL)) 
        fprintf(stderr, "sigaction error\n");
  prctl(PR_SET_PDEATHSIG, SIGHUP);
  while(1) {
     printf("."); fflush(stdout);
     sleep(1);  
    }
 }

 void inform_about_parent_death(int i)  {
  printf("Process is dead. Restart!\n");
  forking_process();
 }

 int main (void) {
  forking_process();
  return EXIT_SUCCESS;
 }

このアプリケーションを実行し、別の端末で子プロセスを強制終了すると、子プロセスが作成されます。親プロセスを一度強制終了すると、シグナルハンドラが開始され、fork() が呼び出されます。親プロセスを再度強制終了すると、シグナル ハンドラが応答しませんでした。つまり、最初のプロセスの prctl() は機能しますが、2 番目の子プロセスの prctl() は機能しません。なぜそれが起こるのですか?プログラムを修正するにはどうすればよいですか?

4

0 に答える 0