Java Processes – How to Kill Java Processes

killpipeprocess

I'm working on a computationally heavy code that – for now – crashes a lot, but I'm still working on it 🙂 When it crashes, I can't close the GUI window; I have to open a shell and kill -9 the process.

It is a Java process and it is easy to find:

nkint@zefiro:~$ ps aux | grep java
nkint   2705 16.6  1.0 460928 43680 ?        Sl   12:23   0:08 /usr/lib/jvm/java-6-sun-1.6.0.26/bin/java -Djava.library.path=something something
nkint   2809  0.0  0.0   4012   776 pts/0    S+   12:24   0:00 grep --color=auto java
nkint@zefiro:~$ kill -9 2705

Now it is easy but quite a mechanical task. So normally i wait for about 7-8 processes to crash, and then kill -9 each of them.

I want to do this in an automatic way. I think that it should be easy to pipe some commands to take the id of the (n-1) results of ps aux | grep java and kill it but I don't have any idea where to start.

Can anyone give me any hints?

Best Answer

A few more pipes will get you where you want to be. Here's how I'd do it:

search_terms='whatever will help find the specific process' 

kill $(ps aux | grep "$search_terms" | grep -v 'grep' | awk '{print $2}')

Here's what's happening:

grep -v 'grep' excludes the grep process from the the results.

awk '{print $2}' prints only the 2nd column of the output (in this case the PID)

$(...) is command substitution. Basically the result from the inner command will be used as an argument to kill

This has the benefit of finer control over what is killed. For example, if you're on a shared system you can edit the search terms so that it only attempts to kill your own java processes.

Related Question