gg.kaspersky gg.kaspersky - 29 days ago 10x
Linux Question

Prevent process from killing itself using pkill

I'm writing a stop routine for a start-up service script:

rm -f $PIDFILE
pkill -f $DAEMON || return 1
return 0

The problem is that pkill (same with killall) also matches the process representing the script itself and it basically terminates itself. How to fix that?


You can explicitly filter out the current PID from the results:

kill $(pgrep -f $DAEMON | grep -v ^$$\$)

To correctly use the -f flag, be sure to supply the whole path to the daemon rather than just a substring. That will prevent you from killing the script (and eliminate the need for the above grep) and also from killing all other system processes that happen to share the daemon's name.