SIGINT 信号后进程终止

Process dies after SIGINT signal

我不明白这里发生了什么,我有一个 parent 进程处理 SIGINT 信号,然后生成一个 child。当我按下 Ctrl+C 时,我期望的是两个进程都将打印 "SIGINT received" 然后继续,但事实证明 parent 进程在收到 SIGINT 后死亡,但 child 仍然存在。看不懂。

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/signal.h>
#include <string.h>

void handler (int sig) {
  printf("SIGINT received\n");
}

void child() {
  while (1) {
    printf("I'm the child\n");
    sleep(1);
  }

  exit(0);
}

int main(int argc, char *argv[]) {
  struct sigaction act;

  memset(&act, 0, sizeof(act));

  act.sa_handler = &handler;
  // Link SIGINT with the handler
  sigaction(SIGINT, &act, NULL);

  // Create child
  if (fork() == 0) child();

  wait(NULL);

  return 0;
}

执行示例:

$ ./test_signals
I'm the child
^CSIGINT received
I'm the child
SIGINT received
$ I'm the child
I'm the child

所以两个进程都处理 SIGINT,但是 parent 死亡,而 child 继续...

parent 进程在主函数中被阻塞,并在收到信号后对其进行处理,并且 returns 从对 wait 的调用中出错。

child 只是在 while 处理 SIGINT 中循环。当在原处处理代码 returns(可能在睡眠中被阻塞)并继续循环。

该代码可以说明发生的情况:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/signal.h>
#include <string.h>
#include <sys/errno.h>

void handler (int sig) {
  printf("SIGINT received %d\n",getpid());
}

void child() {
  while (1) {
    printf("I'm the child\n");
    sleep(1);
  }

  exit(0);
}

int main(int argc, char *argv[]) {
  struct sigaction act;

  memset(&act, 0, sizeof(act));

  act.sa_handler = &handler;
  // Link SIGINT with the handler
  sigaction(SIGINT, &act, NULL);

  // Create child
  if (fork() == 0) child();

  int r = wait(NULL);
  if (r==-1 && errno==EINTR) printf("signal probably received in parent\n");

  return 0;
}

请注意,禁止在信号处理程序中调用 printf