waitpid()¶
Purpose¶
waitpid() waits for a child process to change state and reaps it.
It is commonly used after fork() to avoid zombie processes.
Header¶
Prototype¶
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
WNOHANGwithout a loop or state machine. - Ignoring abnormal exits or signals.