Can't set signal handler for SIGQUIT in child process started from Java

守給你的承諾、 提交于 2019-12-24 07:36:01

问题


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();


来源:https://stackoverflow.com/questions/42982014/cant-set-signal-handler-for-sigquit-in-child-process-started-from-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!