wait
是 Linux 系统中的一个系统调用,用于父进程等待其一个或多个子进程结束,并获取它们的退出状态。以下是对 wait
系统调用的详细解释:
wait
是操作系统提供的一种接口,允许父进程查询其子进程的状态。wait
或 waitpid
来获取子进程的退出状态并清理相关资源。wait
,父进程可以及时回收子进程的资源,避免资源泄漏。以下是一个使用 wait
的简单示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程
printf("子进程开始执行
");
sleep(3); // 模拟子进程执行任务
printf("子进程结束
");
exit(EXIT_SUCCESS);
} else { // 父进程
int status;
printf("父进程等待子进程结束
");
wait(&status); // 等待子进程结束
if (WIFEXITED(status)) {
printf("子进程正常退出,退出状态码: %d
", WEXITSTATUS(status));
} else {
printf("子进程异常退出
");
}
}
return 0;
}
wait
或 waitpid
,子进程结束后会变成僵尸进程。解决方法是确保父进程在适当的时候调用 wait
或 waitpid
。waitpid
并指定子进程的 PID。如果父进程有多个子进程,并且只想等待特定的子进程,可以使用 waitpid
:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid1 = fork();
if (pid1 < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid1 == 0) { // 子进程1
printf("子进程1开始执行
");
sleep(2);
printf("子进程1结束
");
exit(EXIT_SUCCESS);
}
pid_t pid2 = fork();
if (pid2 < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid2 == 0) { // 子进程2
printf("子进程2开始执行
");
sleep(3);
printf("子进程2结束
");
exit(EXIT_SUCCESS);
} else { // 父进程
int status;
printf("父进程等待子进程1结束
");
waitpid(pid1, &status, 0); // 等待子进程1结束
if (WIFEXITED(status)) {
printf("子进程1正常退出,退出状态码: %d
", WEXITSTATUS(status));
}
printf("父进程等待子进程2结束
");
waitpid(pid2, &status, 0); // 等待子进程2结束
if (WIFEXITED(status)) {
printf("子进程2正常退出,退出状态码: %d
", WEXITSTATUS(status));
}
}
return 0;
}
通过以上示例,可以看到如何使用 wait
和 waitpid
来管理子进程的生命周期,并获取它们的退出状态。
领取专属 10元无门槛券
手把手带您无忧上云