Linux – Killing all the process of a command except first process

duplicatelinuxprocessprocess-management

I am sometimes stuck in a situation where a script/command kept in Cron runs more than once because of some reasons (the first instance is not completed fully, the second instance of the same process starts) and at some point of time these processes increase a lot and show system hanging etc. So, what I want as a temporary solution here is to check if there are more than one instances of the script/command say,

ps -ef | pgrep -f 'DELETE OPERATION_CONTEXT'

or directly kill all the processes of this command

ps -ef | pkill -f 'DELETE OPERATION_CONTEXT'

But I want an idea how I can kill all the processes of pgrepped command except for the first process (this would let one of the process to keep working and all other duplicates to get killed).

Best Answer

You can do this for example with:

OLDEST_PID=$(pgrep -o 'DELETE OPERATION_CONTEXT')
test $OLDEST_PID && pgrep 'DELETE OPERATION_CONTEXT' | grep -vw $OLDEST_PID | xargs -r kill

The first line finds the oldest PID. The second line checks first if $OLDEST_PID contains something. If yes, it list all matching processes, filters the $OLDEST_PID out and kill them (if any remain).

A better way is to avoid duplicated processes by adding lockfiles to the cron script like in this question.

Related Question