wait
是 Linux 系统调用,用于父进程等待其子进程结束并收集其退出状态。以下是对 wait
的详细解释:
当一个进程创建了另一个进程(子进程)时,子进程会继承父进程的许多属性,但它们是两个独立的进程。子进程终止后,它的资源(除了与父进程共享的部分)通常会被系统回收,但子进程的退出状态会保留一段时间,以便父进程查询。wait
系统调用就是用来让父进程等待并获取子进程的退出状态的。
wait
,子进程终止后会变成僵尸进程,占用系统资源。wait
系统调用有多个变体,常用的有:
wait(int *status)
:等待任意一个子进程结束,并获取其退出状态。waitpid(pid_t pid, int *status, int options)
:等待特定子进程结束,可以指定等待的子进程 ID 和选项。以下是一个简单的示例,展示如何使用 wait
系统调用:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid == 0) {
// 子进程
printf("Child process, PID: %d
", getpid());
sleep(2); // 模拟子进程执行任务
printf("Child process exiting
");
exit(EXIT_SUCCESS);
} else {
// 父进程
int status;
printf("Parent process, PID: %d, waiting for child...
", getpid());
wait(&status); // 等待子进程结束
if (WIFEXITED(status)) {
printf("Child process exited with status %d
", WEXITSTATUS(status));
} else {
printf("Child process did not exit successfully
");
}
}
return 0;
}
wait
,子进程终止后会变成僵尸进程。解决方法是在父进程中调用 wait
或 waitpid
。waitpid
并指定子进程的 PID 来等待特定的子进程。waitpid
的选项 WNOHANG
来实现非阻塞等待,或者结合 sleep
和循环来实现超时等待。wait
系统调用是 Linux 进程管理中的重要工具,用于父进程等待子进程结束并获取其退出状态。正确使用 wait
可以避免僵尸进程,确保资源得到正确回收,并实现进程间的同步和结果收集。
领取专属 10元无门槛券
手把手带您无忧上云