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.
-
java runs in a virtual machine, it's like a closed box; by no means you kill a system process in pure java. There might be options invoking native interfaces. See JNI or JNA – digital illusion Jun 15 '11 at 10:33
-
What trick resolved your issue ? I am also facing the same issue. I have described details here: http://stackoverflow.com/questions/27942679/how-to-terminate-a-process-normally-created-using-processbuilder – Bilal Ahmed Yaseen Jan 15 '15 at 07:35
-
1@BilalAhmedYaseen I used the selected answer and the answer by Lakshitha Ranasingha, they did the trick for me. – Jeel Shah May 26 '16 at 11:57
8 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 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.

- 11,553
- 8
- 64
- 88

- 6,840
- 3
- 46
- 63
-
I am also facing the same issue. I have described details here: http://stackoverflow.com/questions/27942679/how-to-terminate-a-process-normally-created-using-processbuilder – Bilal Ahmed Yaseen Jan 15 '15 at 07:34
-
1And have in mind that, usually, you may need admin privileges to kill a process. Maybe, you also want to add the windows command for doing it in your answer. – PhoneixS Aug 02 '18 at 08:03
On Windows, you could use this command.
taskkill /F /IM <processname>.exe
To kill it forcefully, you may use;
Runtime.getRuntime().exec("taskkill /F /IM <processname>.exe")

- 4,321
- 1
- 28
- 33
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 " +....);

- 2,031
- 1
- 18
- 24
-
-
8
-
2"kill -9" is not always a good idea as it doesn't give the process being killed a chance to cleanly come down. – Jerome Provensal Dec 04 '18 at 18:57
-
@JeromeProvensal What if you are making an antivirus? You __don't__ want to give the virus a chance to cleanly come down! – Lumin Jan 24 '19 at 07:39
-
1@Holyprogrammer, agreed but I wasn't talking about a virus but a process that you control/understand. – Jerome Provensal Jan 25 '19 at 15:05
-
With Java 9
, we can use ProcessHandle which makes it easier to identify and control native processes:
ProcessHandle
.allProcesses()
.filter(p -> p.info().commandLine().map(c -> c.contains("firefox")).orElse(false))
.findFirst()
.ifPresent(ProcessHandle::destroy)
where "firefox" is the process to kill.
This:
First lists all processes running on the system as a
Stream<ProcessHandle>
Lazily filters this stream to only keep processes whose launched command line contains "firefox". Both
commandLine
orcommand
can be used depending on how we want to retrieve the process.Finds the first filtered process meeting the filtering condition.
And if at least one process' command line contained "firefox", then kills it using
destroy
.
No import necessary as ProcessHandle
is part of java.lang
.

- 54,987
- 21
- 291
- 190
Accidentally i stumbled upon another way to do a force kill on Unix (for those who use Weblogic). This is cheaper and more elegant than running /bin/kill -9 via Runtime.exec().
import weblogic.nodemanager.util.Platform;
import weblogic.nodemanager.util.ProcessControl;
...
ProcessControl pctl = Platform.getProcessControl();
pctl.killProcess(pid);
And if you struggle to get the pid, you can use reflection on java.lang.UNIXProcess, e.g.:
Process proc = Runtime.getRuntime().exec(cmdarray, envp);
if (proc instanceof UNIXProcess) {
Field f = proc.getClass().getDeclaredField("pid");
f.setAccessible(true);
int pid = f.get(proc);
}

- 430
- 4
- 10
-
There is a non-hack, cross platform way how to obtain PID for any JVM application, check http://mostly-about-java.blogspot.co.uk/2013/06/how-to-get-process-id-for-any-jvm.html – Espinosa Jul 03 '13 at 13:49
-
@Brian Gordon Yes, I know, using sun.jvmstat.monitor.* is also not a perfect solution, not part of the supported, public interface, but still better and portable then rely on external unix tools or expecting Process to be UNIXProcess, which on Windows it is not and perhaps will not be in future Java release seven on Unix. – Espinosa Nov 20 '13 at 19:05
-
@Espinosa Depends on what are you trying to achieve. destroy() on Windows does force the kill, so this hack is not needed there (and btw Weblogic does have a class for Windows too). Remember we have to write such ugly code only because of shortsighted JVM implementation and API design defect. – chukko Mar 11 '15 at 18:21
-
Continuation: In the end it is just matter of taste - for java process manager i would maybe use your solution - but to workaround specific bug i prefer smaller/quicker/dirtier "patch" of mine to your theoretically cleaner but iterative and more cumbersome solution. Each nail requires a different hammer. – chukko Mar 11 '15 at 18:30
Try it:
String command = "killall <your_proccess>";
Process p = Runtime.getRuntime().exec(command);
p.destroy();
if the process is still alive, add:
p.destroyForcibly();

- 54,987
- 21
- 291
- 190

- 59
- 1
- 2
- 11
-
-
After `Runtime.exec` has returned, you don't know how far the `killall` process has progressed, and then you immediately kill the `killall`, maybe before it had the chance to do anything. Instead of `destroy`, you should rather `waitFor()` it and check its exit status. – EndlosSchleife Jul 15 '20 at 09:59
You can kill a (SIGTERM) a windows process that was started from Java by calling the destroy method on the Process object. You can also kill any child Processes (since Java 9).
The following code starts a batch file, waits for ten seconds then kills all sub-processes and finally kills the batch process itself.
ProcessBuilder pb = new ProcessBuilder("cmd /c my_script.bat"));
Process p = pb.start();
p.waitFor(10, TimeUnit.SECONDS);
p.descendants().forEach(ph -> {
ph.destroy();
});
p.destroy();

- 63
- 6
It might be a java interpreter defect, but java on HPUX does not do a kill -9, but only a kill -TERM.
I did a small test testDestroy.java:
ProcessBuilder pb = new ProcessBuilder(args);
Process process = pb.start();
Thread.sleep(1000);
process.destroy();
process.waitFor();
And the invocation:
$ tusc -f -p -s signal,kill -e /opt/java1.5/bin/java testDestroy sh -c 'trap "echo TERM" TERM; sleep 10'
dies after 10s (not killed after 1s as expected) and shows:
...
[19999] Received signal 15, SIGTERM, in waitpid(), [caught], no siginfo
[19998] kill(19999, SIGTERM) ............................................................................. = 0
...
Doing the same on windows seems to kill the process fine even if signal is handled (but that might be due to windows not using signals to destroy).
Actually i found Java - Process.destroy() source code for Linux related thread and openjava implementation seems to use -TERM as well, which seems very wrong.
-
1Using -TERM is correct because it lets the process clean up after itself. Using kill -9 just nukes the poor thing. The really correct way is to use kill -TERM, wait some time and then kill -9 if it's still around. – Urban Vagabond Apr 11 '14 at 00:47
-
1Yes - but JVM unfortunately does not issue a following kill -9, thus gives you no way to force the kill. Thus still being very wrong. There should be a force option, otherwise this is useful only for well behaving processes - i.e. for sunny days only. – chukko Apr 29 '14 at 17:48
-
1
-
Indeed it does - albeit it is only available in Java 8 (whcih was not available on the project i was developing for). I just noticed that Haysa Rodrigues already added that answer. – chukko Dec 13 '17 at 21:54