Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trap a SIGNAL in a java application initialized using a bash script

I am catching an INT signal in java using the following code:

    Signal.handle(new Signal("INT"), new SignalHandler () {
        public void handle(Signal sig) {

            log.warn("Received SIGINT signal. Will teardown.");

            task.tearDown();

            // Force exit anyway
            System.exit(1);
        }
      });

When I am using java -jar file.jar to start my application I can catch the signal sent with with kill -INT PID.

If I call java -jar file.jar & (jvm runs in the background), I can't catch the signal sent with kill -INT.

Any ideas?

Thanks.

like image 970
simao Avatar asked Nov 10 '10 17:11

simao


People also ask

What is trap command in shell scripting?

The trap command lets you to regulate how a program responds to a signal. A signal is an asynchronous communication consisting of a number that can be delivered from one process to another or from the operating system to a process if particular keys are pushed or if anything unusual occurs.

What is the syntax of trap command?

The syntax for the trap command is "trap COMMAND SIGNALS...", so unless the command you want to execute is a single word, the "command" part should be quoted. Note that if you send a kill -9 to your script, it will not execute the EXIT trap before exiting.


1 Answers

Works for me. Are you sure you are killing the right pid? On Unix you can use $! to get the pid of the last process you launched.

$ java -jar file.jar &
[1] 25573

$ kill -INT $!
Received SIGINT signal. Will teardown.

Update:

If you are launching this in the background via a shell script, the OS will create a new process group which will be immune to keyboard-generated signals such as SIGINT. Only processes whose process group ID matches the current terminal's process group ID can receive these signals.

So try running it within the current terminal's process group like this:

. ./script.sh

You will then be able to send SIGINT.

More information about job control here.

like image 95
dogbane Avatar answered Sep 24 '22 16:09

dogbane