I'm writing a stop routine for a start-up service script:
do_stop()
{
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?
The pkill command works similarly, but only closes all child processes and leaves the parent process alive. You can also provide this with switch -9. For example, pkill -9 httpd closes all child processes of the webserver.
The main difference between these tools is that kill terminates processes based on Process ID number (PID), while the killall and pkill commands terminate running processes based on their names and other attributes.
pkill is a command-line utility that sends signals to the processes of a running program based on given criteria. The processes can be specified by their full or partial names, a user running the process, or other attributes.
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.
pkill -f
accepts a full blown regex. So rather than pkill -f $DAEMON
you should use:
pkill -f "^"$DAEMON
To make sure only if process name starts with the given daemon name then only it is killed.
A better solution will be to save pid (Proces Id) of the process in a file when you start the process. And for the stopping the process just read the file to get the process id to be stopped/killed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With