Can't set signal handler for SIGQUIT in child

2019-07-27 04:14发布

问题:

This is a follow up question to this one.

Take this simple example:

public class Main
{
    public static void main(String[] args) throws Exception
    {
        Runtime.getRuntime().exec("./child");

        // This is just so that the JVM does not exit
        Thread.sleep(1000 * 1000);
    }
}

And here's the child process:

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

void handle_sigquit(int sig) {
  printf("Signal %d received\n", sig);
  exit(1);
}

int main(int argc, char **argv) {
  signal(SIGQUIT, &handle_sigquit);
  sleep(1000);
}

As you can see, I am explicitly setting up a signal handler in the child process.

When I run this process from a shell, I can send it a SIGQUIT; the signal is received and processed properly. However if I start the process from Java (I am using openjdk6 on Linux) the signal is not delivered. Why is this?

回答1:

java (OpenJDK 6) blocks SIGQUIT in subprocesses by default. Blocked signals remain blocked across fork and exec. You can see this on Linux by looking in the procfs status file for your child process:

$ grep Sig /proc/11246/status
SigPnd: 0000000000000000
SigBlk: 0000000000000004
SigIgn: 0000000000000000
SigCgt: 0000000000000000

You can unblock SIGQUIT in your non-threaded process with:

sigemptyset(&set);
sigaddset(&set, SIGQUIT);
sigprocmask(SIG_UNBLOCK, &set, NULL);

Note that your printfs won't appear in the terminal window; java will replace a subprocess's stdin, stdout, and stderr with pipes, and to read a process's stdout you'd do something like

Process p=Runtime.getRuntime().exec("./child");
InputStream stdout = p.getInputStream();