Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killing a process using Java

Tags:

java

process

I would like to know how to "kill" a process that has started up. I am aware of the Process API, but I am not sure, If I can use that to "kill" an already running process, such as firefox.exe etc. If the Process API can be used, can you please point me into the correct direction? If not, what are the other available options? Thanks.

like image 761
Jeel Shah Avatar asked Jun 15 '11 10:06

Jeel Shah


People also ask

How do you kill a Java process gracefully?

Graceful-kill-java allows you to gracefully kill java processes, which 'taskkill pid' and 'wmic ... call terminate' cannot do. TL;DR Use the command graceful-kill-java. bat [command line partial text] to kill all java processes whose command line contains the partial text.


1 Answers

If you start the process from with in your Java application (ex. by calling Runtime.exec() or ProcessBuilder.start()) then you have a valid Process reference to it, and you can invoke the destroy() method in Process class to kill that particular process.

But be aware that if the process that you invoke creates new sub-processes, those may not be terminated (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4770092).

On the other hand, if you want to kill external processes (which you did not spawn from your Java app), then one thing you can do is to call O/S utilities which allow you to do that. For example, you can try a Runtime.exec() on kill command under Unix / Linux and check for return values to ensure that the application was killed or not (0 means success, -1 means error). But that of course will make your application platform dependent.

like image 166
Yohan Liyanage Avatar answered Sep 20 '22 23:09

Yohan Liyanage