Cannot catch SIGINT signal in a producer-consumer

2019-07-04 11:22发布

问题:

I am writing a program for a producer-consumer problem.

Producer produces data and pushes data into boost::spsc_queue and the consumer processes it.

In consumer thread, I am using JNI to call some java functions from my code written in c++.

I am initializing and creating JVM in the function itself called by the consumer thread and then the event loop starts in which it pops data from boost::spsc_queue and process it.

Now, I want to catch SIGINT signal, so I have written a signal_handler and register it in my main() function. But it is not working.

If I comment out all JNI stuff and just start a loop while(1){} there in the function called by consumer thread, then it is catching SIGINT and working as it is supposed to work.

Is something more which I need to take care for JVM or JNI stuff? Shall I try the same thing after initializing and creating JVM in the main thread? Does it make sense?

回答1:

It seems, you need the -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.

You can specify such options in the JavaVMInitArgs which you pass to JNI_CreateJavaVM(…).



回答2:

Yes, JVM uses signal handlers for its own purpose, that's why you need to care about signal chaining specially. Read more >