Search code examples
csignalsposix

How to fix 'No such process' error from kill function on negation of pid


Attempting to write a signal handler for the SIGINT signal. I want a new SIGINT to be sent to a process group specified by a pid. (using the 'kill' function from signals.h).

The manpages for the kill function man 2 kill indicate that a negative pid will send a signal to the whole process group.

Previously I had this which only send the signal to the pid and it worked fine. The signal was sent and the process properly reacted.

void handle_sigint(int sig){
  pid_t pid = getprocesspid();
  if(kill(pid, sig) < 0){
    //Not taken
  }
}

However when I negate the pid, the kill function returns -1 and errors out with the "No such process" error.

void handle_sigint(int sig){
  pid_t pid = getprocesspid();
  if(kill(-pid, sig) < 0){
    //Errors out
  }
}

This is really odd to me. I can verifed that the pid is correct for the process. However, each time after I negate the pid the program crashes


Solution

  • kill(-pid, sig) will send the signal to the process group pid. kill will error with ESRCH if (Posix):

    ESRCH

    No process or process group can be found corresponding to that specified by pid.

    Not all process IDs are process group IDs.

    You can get the process group id of a process with pid_t getpgid(pid_t pid), i.e.

    pid_t pid = getprocesspid();
    pid_t pgid = getpgid(pid);
    
    if (pgid == -1) {
        // getpgid errored
    }
    
    if (kill(-pgid, sig) < 0){
        //Errors out
    }