Search code examples
clinuxforkkill

Is Killing Child Process PID Guaranteed Safe After fork()?


Consider the following situation:

  1. I use fork() to create a child process from my program
  2. Parent process receives the PID as 1234.
  3. Child process then calls execvp("myotherprogram", some_args);

myotherprogram is expected to run indefinitely until it receives SIGTERM (or higher), but, under some circumstances (e.g. missing file) it will just print an error and abort.

When the parent process receives an event, it wants to kill the child process again by calling:

const int kill_result = kill(1234, SIGTERM);

If myotherprogram exited early, is kill(1234, SIGTERM) going to be safe, or can the OS recycle the PID and I potentially kill a random process?


Solution

  • The PID can't be reused until the parent calls one of the wait functions to get its exit status; until this happens, the process stays around as a "zombie". So you should have a SIGCHLD handler that calls waitpid() to get the exit status. This handler should disable the code that calls kill(), since it no longer necessary and could kill a different process.

    Make sure you're not ignoring SIGCHLD; this prevents zombies and causes the exiting process to disappear immediately.

    Note that except for the root user, you can only kill processes that are under your same userid. So the chance that the PID will be reused by a process that you can kill is very low (unless your program runs as root).