Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I kill processes in Java without forcing it?

Tags:

java

I have a Java program that runs a number of other programs. Once the user is finished they have a button to kill all processes, this should kill everything that is running but it should do it with forcing them. At least one of these other processes is also written in Java and has a number of shutdown hooks as it automatically saves a preferences file on exit and kills processes it has started itself, such as.

    Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        if (process != null)
            process.destroy();
      }
    }

When the main process calls destroy the above code is not run on the subprocess. Is there anyway that I can terminate the processes so this will still run?

I am porting from Perl which does it will the kill(9,@kill_process);

Thanks.

like image 877
A Jackson Avatar asked Sep 23 '26 10:09

A Jackson


2 Answers

Kill signal 9 (SIGKILL) tells the operating system to kill the process. The process gets no notification in advance that this is going to happen and cannot do any cleanup because of it.

process.destroy() is the equivalent of Perl's kill(9,@kill_process);, and your old process wouldn't have been doing any cleanup either.

Kill signal 15 (SIGTERM) will tell a process to kill itself.

like image 173
Powerlord Avatar answered Sep 26 '26 17:09

Powerlord


There are couple of ways how to communicate with application. One of the most common is send signal. Command for signal is called kill. Perl code you post use this aproach.

You can send various signals, some of them are handled by application some of them are handled by os. Default signal is HUP. It tell application that "connection to user" was terminated (it actually mean modem hanged ) and it should exit. Nicely behaving application will exit.

If you send signal 9 (this is what your perl code does), OS will terminate application without question.

Another approach is to communicate with application using its default way. So you can send "Ctrl+c" or "Alt+f4" (those are commands with usually end application) to STDIN of the process.

like image 44
pnemec Avatar answered Sep 26 '26 19:09

pnemec