Kill all Java processes for a particular user in Linux
Terminate all Java processes (that spawn from parent Java process) of fps user id, in the sequence of parent process follow by child process.
for ID in `ps -u fps | grep java | awk ‘{print $1}’`
do
kill -9 $ID
done
The ps -u fps | grep java will output all Java processes of fps user id, in an ascending order of PID. As all these Java processes are spawning from a parent Java process, the first PID appears in the output is also PPID of second Java process in the output, and so forth.
So, the for loop will feed the PID in the same sequence to the kill command. When the kill command terminate the first PID, the child process which spawn from this first Java process will lost its parent (orphan process), and subsequent taken by master process (init process with PID 1).
While, this seem to be OK. But, what will happen when there are few tens or hundreds of child processes with same PPID (same parents)? The init process will have to take care of all these orphan processes in a short time (due to the kill command on for loop), and potentially hang up the Linux operating system!
If you have a Linux server which hang up out of sudden, without any hints from the system and application log files, you might need to find out is anyone terminating Linux processes in batch like this!
Now, let’s tweak a bit the for loop, to become like this
for ID in `ps -u fps | grep java | awk ‘{print $1}’ | sort -r`
do
kill -9 $ID
done
The sort -r command will reverse the order of PID output, where the PID will then appear in descending order. This will enable the kill command to terminate the last child process, and all the way up to its parent process!
Category: Tips for linux
