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?
If you want to kill all processes that are named
java
you can use following command:This command sends signals to processes identified by their name.
A few more pipes will get you where you want to be. Here's how I'd do it:
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 tokill
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.
Open a text editor and save this short bash script in your home directory as 'killjava'
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, perhapskill -15
would be more appropriate - see the explanation here.Here is an alternative approach, based on @Dean's earlier answer.
This uses jps to identify the java process.
MainClass is a class in your running java program which contains the main method.
I created this as my Modded minecraft server crashes sometimes and java sticks and wont close got fed up and scripted a sh script that will detect if java is running and attempt to kill them all here is the code if anyone wants it