Skip to content

waitpid()

Purpose

waitpid() waits for a child process to change state and reaps it.

It is commonly used after fork() to avoid zombie processes.

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

Prototype

pid_t waitpid(pid_t pid, int *status, int options);

Minimal Example

int status;
pid_t ret = waitpid(child_pid, &status, 0);
if (ret < 0) {
    perror("waitpid");
    return -1;
}

if (WIFEXITED(status)) {
    int code = WEXITSTATUS(status);
    (void)code;
}

Common Pitfalls

  • Not handling EINTR.
  • Forgetting to reap children.
  • Using WNOHANG without a loop or state machine.
  • Ignoring abnormal exits or signals.