| 函數 | 頭文件 | 語義 |
| wait(int *status) | sys/wait.h | 掛起調用進程,**任一**子進程狀態改變返回 |
| waitpid(pid_t pid, int *status, int options) | sys/wait.h | 等待**指定**子進程,options 控制行為(WNOHANG 非阻塞等) |
| waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options) | sys/wait.h | 更精確控制等待對象(進程/進程組/所有) |
狀態改變三類事件
- 子進程終止(正常 exit 或異常崩潰)
- 信號導致子進程停止
- 信號恢復子進程運行(SIGCONT)
僵屍進程與 wait 的關系
- 子進程終止、父進程未
wait → 僵屍態,佔用進程表項
wait 回收僵屍進程資源,釋放進程表項
- 父進程先終止 → 僵屍子進程被 init (PID 1) 收養,自動
wait 清理
- 進程表滿 → 無法創建新進程
wait 詳解
pid_t wait(int *status);
- 掛起父進程,直到子進程終止
- 子進程已終止 → 立即返回
status 存儲終止狀態(可為 NULL)
- 返回:子進程 PID,錯誤 -1 (
errno)
狀態檢查宏
WIFEXITED(status) // 正常退出
WEXITSTATUS(status) // 獲取 exit code
WIFSIGNALED(status) // 信號終止
WTERMSIG(status) // 獲取信號編碼
WIFSTOPPED(status) // 信號停止
WSTOPSIG(status) // 獲取停止信號
WIFCONTINUED(status) // SIGCONT 恢復
完整示例
#include
#include
#include
#include
void check_exit(int status) {
if (WIFEXITED(status)) printf("exit\n");
else if (WIFSIGNALED(status)) printf("killed by signal\n");
else if (WIFSTOPPED(status)) printf("stopped by signal\n");
else if (WIFCONTINUED(status)) printf("continued\n");
}
int main() {
pid_t pid = fork();
if (pid < 0) { perror("fork"); exit(1); }
if (pid == 0) { printf("child exit\n"); exit(0); }
int status;
if (wait(&status) != pid) { perror("wait"); exit(1); }
check_exit(status);
return 0;
}
關鍵差異總結
wait = waitpid(-1, &status, 0)
waitpid 支持非阻塞 (WNOHANG)、指定 PID/進程組
waitid 提供 siginfo_t 詳細信息,支持 P_PID/P_PGID/P_ALL
- 上一篇文章: Linux 文件系統核心:五大文件類型與權限模型深度解析
- 下一篇文章: Linux 內存鎖定機制:mlock/munlock/mlockall/munlockall 實現確定性與安全性
Copyright ©
程式碼之家 All Rights Reserved