80

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.

3
  • 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 Jun 15, 2011 at 10:33
  • What trick resolved your issue ? I am also facing the same issue. I have described details here: stackoverflow.com/questions/27942679/… Jan 15, 2015 at 7:35
  • 1
    @BilalAhmedYaseen I used the selected answer and the answer by Lakshitha Ranasingha, they did the trick for me.
    – Jeel Shah
    May 26, 2016 at 11:57

8 Answers 8

64

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.

3
  • I am also facing the same issue. I have described details here: stackoverflow.com/questions/27942679/… Jan 15, 2015 at 7:34
  • 1
    And 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 2, 2018 at 8:03
  • + destroyForcibly() seems to be the equivalent of unix "kill -9" or windows "taskkill /F", while destroy() might perform a controlled process shutdown by a shutdown-handler, which can consider child processes. Jan 27 at 17:05
62

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")
0
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 " +....);
6
  • Works on Win7 64 bits :D Mar 4, 2015 at 17:20
  • 8
    for linux , I used "pkill firefox" May 7, 2015 at 9:21
  • 2
    "kill -9" is not always a good idea as it doesn't give the process being killed a chance to cleanly come down. Dec 4, 2018 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, 2019 at 7:39
  • 1
    @Holyprogrammer, agreed but I wasn't talking about a virus but a process that you control/understand. Jan 25, 2019 at 15:05
21

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 or command 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.

4

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);
}
4
  • There is a non-hack, cross platform way how to obtain PID for any JVM application, check mostly-about-java.blogspot.co.uk/2013/06/…
    – Espinosa
    Jul 3, 2013 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, 2013 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, 2015 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, 2015 at 18:30
3

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();
3

Try it:

String command = "killall <your_proccess>";
Process p = Runtime.getRuntime().exec(command);
p.destroy();

if the process is still alive, add:

p.destroyForcibly();
2
  • Needs to be noted that this is only available on Java 8.
    – chukko
    Dec 13, 2017 at 21:57
  • 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. Jul 15, 2020 at 9:59
2

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.

4
  • 1
    Using -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. Apr 11, 2014 at 0:47
  • 1
    Yes - 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, 2014 at 17:48
  • 1
    Isn't destroyForcibly() send kill -9? Dec 12, 2017 at 19:32
  • 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, 2017 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.