Killing a process using Java
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.
--------------------------------
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.
-------------------------------
In Windows you probably have to use this command
taskkill /F /IM <processname>.exe
to kill it forcefully. So it will be
Runtime.getRuntime().exec("taskkill /F /IM <processname>.exe")
-----------------------------
AFAIU java.lang.Process is the process created by java itself (like Runtime.exec('firefox'))
You can use system-dependant commands like
Runtime rt =Runtime.getRuntime();if(System.getProperty("os.name").toLowerCase().indexOf("windows")>-1)
rt.exec("taskkill "+....);else
rt.exec("kill -9 "+....);