Kill Java processes
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?
Solution 1:
If you want to kill all processes that are named java
you can use following command:
killall -9 java
This command sends signals to processes identified by their name.
Solution 2:
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.
Solution 3:
Open a text editor and save this short bash script in your home directory as 'killjava'
#! /bin/bash
# Kill Java process
# Determine the pid
PID=`ps -C java -o pid=`
kill -9 $PID
Then chmod u+x ~/killjava
in a terminal so you can execute the file.
Then you can just call ~/killjava
from a terminal and your Java process will be stone dead. You may wish to consider what other resources your killing of the Java process in this way (such as database connections) will be affected. For example, perhaps kill -15
would be more appropriate - see the explanation here.
Solution 4:
Here is an alternative approach, based on @Dean's earlier answer.
This uses jps to identify the java process.
kill $(jps | grep <MainClass> | awk '{print $1}')
MainClass is a class in your running java program which contains the main method.