Killing a process using Java
Asked Answered
S

8

79

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.

Sitar answered 15/6, 2011 at 10:29 Comment(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 JNAErwin
What trick resolved your issue ? I am also facing the same issue. I have described details here: #27943179Mozellemozes
@BilalAhmedYaseen I used the selected answer and the answer by Lakshitha Ranasingha, they did the trick for me.Sitar
L
63

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.

Levan answered 15/6, 2011 at 10:37 Comment(3)
I am also facing the same issue. I have described details here: #27943179Mozellemozes
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.Gand
+ 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.Pifer
K
61

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")
Kristoforo answered 6/7, 2012 at 17:17 Comment(0)
D
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 " +....);
Dost answered 15/6, 2011 at 10:38 Comment(6)
Works on Win7 64 bits :DHanan
for linux , I used "pkill firefox"Yser
"kill -9" is not always a good idea as it doesn't give the process being killed a chance to cleanly come down.Galactose
@JeromeProvensal What if you are making an antivirus? You don't want to give the virus a chance to cleanly come down!Hodden
@Holyprogrammer, agreed but I wasn't talking about a virus but a process that you control/understand.Galactose
@JeromeProvensal :)Hodden
K
23

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.

Kinson answered 26/9, 2018 at 21:7 Comment(0)
R
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);
}
Rectus answered 2/7, 2013 at 16:19 Comment(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/…Lenes
@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.Lenes
@Lenes 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.Rectus
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.Rectus
B
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();
Boschbok answered 17/3, 2017 at 1:41 Comment(2)
Needs to be noted that this is only available on Java 8.Rectus
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.Sausa
C
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();
Carafe answered 26/6, 2018 at 4:37 Comment(0)
R
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.

Rectus answered 25/4, 2013 at 12:23 Comment(4)
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.Teem
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.Rectus
Isn't destroyForcibly() send kill -9?Rumba
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.Rectus

© 2022 - 2024 — McMap. All rights reserved.