Wait & Waitpid

Notes on Wait & Waitpid


Zombies

Wait / Waitpid

Either of wait or waitpid can be used to remove zombies.

wait (and waitpid in it's blocking form) temporarily suspends the execution of a parent process while a child process is running. Once the child has finished, the waiting parent is restarted.

Declarations:

    #include <sys/types.h>
    #include <sys/wait.h>

    pid_t wait(int *statloc);
    /* returns process ID if OK, or -1 on error */

    pid_t waitpid(pid_t pid, int *statloc, int options);
    /* returns process ID : if OK,
     *          0         : if non-blocking option && no zombies around
     *          -1        : on error
     */

The statloc argument can be one of two values:

wait()waitpid()
wait blocks the caller until a child process terminates
waitpid can be either blocking or non-blocking:
  • If options is 0, then it is blocking
  • If options is WNOHANG, then is it non-blocking
if more than one child is running then wait() returns the first time one of the parent's offspring exits
waitpid is more flexible:

  • If pid == -1, it waits for any child process. In this respect, waitpid is equivalent to wait
  • If pid > 0, it waits for the child whose process ID equals pid
  • If pid == 0, it waits for any child whose process group ID equals that of the calling process
  • If pid < -1, it waits for any child whose process group ID equals that absolute value of pid

References