Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent process from killing itself using pkill

Tags:

linux

bash

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?

like image 704
kaspersky Avatar asked Apr 01 '13 09:04

kaspersky


People also ask

Does pkill kill all processes?

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.

Is pkill same as kill?

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.

What does Sudo pkill do?

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.


2 Answers

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.

like image 51
user4815162342 Avatar answered Oct 21 '22 20:10

user4815162342


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.

like image 28
anubhava Avatar answered Oct 21 '22 18:10

anubhava