无法在消费者线程中使用 JNI 的生产者消费者程序中捕获 SIGINT 信号

Cannot catch SIGINT signal in a producer-consumer program where JNI is used in consumer thread

我正在为生产者-消费者问题编写程序。

生产者生产数据并将数据推送到boost::spsc_queue,消费者处理它。

在消费者线程中,我使用 JNI 从我用 C++ 编写的代码中调用一些 java 函数。

initializing and creating JVM 在消费者线程调用的函数本身中,然后事件循环开始,它从 boost::spsc_queue 弹出数据并处理它。

现在,我想捕获 SIGINT 信号,所以我写了一个 signal_handler 并将其注册到我的 main() 函数中。但它不起作用。

如果我注释掉所有 JNI 内容并在消费者线程调用的函数中启动一个循环 while(1){},那么它会捕获 SIGINT 并按预期工作。

我还需要处理 JVM 或 JNI 的东西吗? 在主线程中初始化和创建 JVM 之后,我应该尝试同样的事情吗?有道理吗?

是的,JVM 出于自己的目的使用信号处理程序,这就是您需要特别关注信号链的原因。 Read more >

看来,你需要-Xrs option

-Xrs

Reduces the use of operating system signals by the JVM.

Applications embedding the JVM frequently need to trap signals such as SIGINT or SIGTERM, which can lead to interference with the JVM signal handlers. The -Xrs option is available to address this issue. When -Xrs is used, the signal masks for SIGINT, SIGTERM, SIGHUP, and SIGQUIT are not changed by the JVM, and signal handlers for these signals are not installed.

There are two consequences of specifying -Xrs:

  • SIGQUIT thread dumps are not available.

  • User code is responsible for causing shutdown hooks to run, for example, by calling System.exit() when the JVM is to be terminated.

您可以在传递给 JNI_CreateJavaVM(…)JavaVMInitArgs 中指定此类选项。