Killing a process using Java
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 https://bugs.openjdk.org/browse/JDK-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.
The right way to kill a process in Java
If the process you want to kill has been started by your application
Then you probably have a reference to it (ProcessBuilder.start()
or Runtime.exec()
both return a reference). In this case, you can simply call p.destroy()
. I think this is the cleanest way (but be careful: sub-processes started by p
may stay alive, check Process.destroy does not kill multiple child processes for more info).
The destroyForcibly
should only be used if destroy()
failed after a certain timeout. In a nutshell
- terminate process with
destroy()
- allow process to exit gracefully with reasonable timeout
- kill it with
destroyForcibly()
if process is still alive
If the process you want to kill is external
Then you don't have much choice: you need to pass through the OS API (Runtime.exec
). On Windows, the program to call will be taskkill.exe
, while on Mac and Linux you can try kill
.
Have a look at Support for Process.destroyForcibly() and .isAlive() from Java 8 and Killing a process using Java and Code a Simple Java App to Kill Any Process After a Specified Time for more info.
How to close running process using java?
Runtime.exec(...) returns Process
object which consists following methods
- destroy()
- exitValue()
- getErrorStream()
- getInputStream()
- getOutputStream()
- waitFor()
you can call destroy() which kills the subprocess. The subprocess represented by this Process object is forcibly terminated.
or you can kill by passing taskkill /PID <process id>
in Runtime.exec(...)
or kill -9 <process id>
How can I kill a process from a Java application, if I know the PID of this process? I am looking for a cross-platfrom solution
Since Java 9 there's ProcessHandle
which allows interaction with all processes on a system (constrained by system permissions of course).
Specifically ProcessHandle.of(knownPid)
will return the ProcessHandle
for a given PID (technically an Optional
which may be empty if no process was found) and destroy
or destroyForcibly
will attempt to kill the process.
I.e.
long pid = getThePidViaSomeWay();
Optional<ProcessHandle> maybePh = ProcessHandle.of(pid);
ProcessHandle ph = maybePh.orElseThrow(); // replace with your preferred way to handle no process being found.
ph.destroy(); //or
ph.destroyForcibly(); // if you want to be more "forcible" about it
How to find and kill running Win-Processes from within Java?
You can use command line windows tools tasklist
and taskkill
and call them from Java using Runtime.exec()
.
Kill a java process using its Name and not PID
Finally found a easy solution here
jps - Java Virtual Machine Process Status Tool , can be used for killing a java process with its name.
for /f "tokens=1" %i in ('C:\java\jdk-7u45-windows-x64\bin\jps -m ^| find "DummyBroker"') do ( taskkill /F /PID %i )
We can add above in batch file and simply call the batch file from java program.
how to kill a process in java after completion of a job in java
process.destroy()
But it won't have control over the process started from server.bat
those are separately started
Related Topics
Why Does Runtime.Exec(String) Work for Some But Not All Commands
How to Make an Image Move While Listening to a Keypress in Java
What Is an Outofmemoryerror and How to Debug and Fix It
Display Indeterminate Jprogressbar While Batch File Runs
How to Get the Exact Middle of a Screen, Even When Re-Sized
Regex to Match a C-Style Multiline Comment
Why Doesn't Java Send the Client Certificate During Ssl Handshake
Using Switch Statement with a Range of Value in Each Case
How to Write a Custom JSON Deserializer for Gson
Update Jlabel Every X Seconds from Arraylist<List> - Java
How to Maintain Jtable Cell Rendering After Cell Edit
When and How to Use a Threadlocal Variable
Java.Lang.Classnotfoundexception When Running in Intellij Idea