Вопрос

I have a subprocess (running on MacOS) that I want to kill itself if the parent quits, exits, terminates, is killed or crashes. Having followed the advice from How to make child process die after parent exits? I can't get it to quietly kill itself if the parent program crashes. It will go to 100% CPU until I manually kill it.

Here are the key points of the code:

int main(int argc, char *argv[])
{
  // Catch signals
  signal(SIGINT,  interruptHandler);
  signal(SIGABRT, interruptHandler);
  signal(SIGTERM, interruptHandler);
  signal(SIGPIPE, interruptHandler);

  // Create kqueue event filter
  int kqueue_fd = kqueue();
  struct kevent kev, recv_kev;
  EV_SET(&kev, parent_pid, EVFILT_PROC, EV_ADD|EV_ENABLE, NOTE_EXIT, 0, NULL);
  kevent(kqueue_fd, &kev, 1, NULL, 0, NULL);

  struct pollfd kqpoll;
  kqpoll.fd = kqueue_fd;
  kqpoll.events = POLLIN;

  // Start a run loop
  while(processEvents())
  {
    if(kill(parent_pid, 0) == -1)
      if(errno == ESRCH)
        break;

    if(poll(&kqpoll, 1, 0) == 1)
      if(kevent(kqueue_fd, NULL, 0, &recv_kev, 1, NULL))
        break;

    parent_pid = getppid();
    if(parent_pid == 1)
      break;

    sleep(a_short_time);

    // (simple code here causes subprocess to sleep longer if it hasn't
    // received any events recently)
  }
}
Это было полезно?

Решение

Answering my own question here:

The reason for this problem was not down to detecting whether the parent process had died. In processEvents() I was polling the pipe from the parent process to see if there was any communication. When the parent died, poll() returned a value of 1 and the read loop thought there was infinite data waiting to be read.

The solution was to detect whether the pipe had been disconnected or not.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top