Since the answer linked by @Vlad is for Windows, and this question is for linux, here's an answer to that. Linux uses signals to interrupt processes, and you can use kill
to send a signal:
// shut down process with id 123 (can be ignored by the process)
Runtime.getRuntime().exec("kill 123");
// shut down process with id 123 (can not be ignored by the process)
Runtime.getRuntime().exec("kill -9 123");
with kill, you can also send other signals as told in the man page (and it doesn't have to be a killing signal). By default, kill will send a SIGTERM
signal, which tells the process to terminate, but it can be ignored. If you want the process to terminate without the possibility for ignore, SIGKILL
can be used. In the code above, first call uses SIGTERM, the latter one SIGKILL. You can also be explicit about it:
// shut down process with id 123 (can be ignored by the process)
Runtime.getRuntime().exec("kill -SIGTERM 123");
// shut down process with id 123 (can not be ignored by the process)
Runtime.getRuntime().exec("kill -SIGKILL 123");
If you want to operate with name of the target program instead of process id, there's also killall
which will accept the name as a parameter. As the name implies, that would kill all processes that match. Example:
// shuts down all firefox processes (can not be ignored)
Runtime.getRuntime().exec("killall -SIGKILL firefox");