在Linux系统中,等待子进程结束是一个常见的操作,主要通过wait()
和waitpid()
系统调用来实现。以下是关于这个问题的基础概念、优势、类型、应用场景以及可能遇到的问题和解决方法。
父进程与子进程:
等待子进程结束:
wait()
或waitpid()
系统调用来等待其子进程结束。wait()
:waitpid()
:WNOHANG
表示非阻塞)。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) { // 子进程
printf("Child process: PID = %d\n", getpid());
sleep(2);
exit(0);
} else if (pid > 0) { // 父进程
int status;
wait(&status);
printf("Parent process: Child with PID %d has finished.\n", pid);
} else {
perror("fork");
exit(EXIT_FAILURE);
}
return 0;
}
waitpid()
#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) { // 子进程
printf("Child process: PID = %d\n", getpid());
sleep(2);
exit(0);
} else if (pid > 0) { // 父进程
int status;
while (waitpid(pid, &status, WNOHANG) == 0) {
printf("Parent process: Waiting for child...\n");
sleep(1);
}
printf("Parent process: Child with PID %d has finished.\n", pid);
} else {
perror("fork");
exit(EXIT_FAILURE);
}
return 0;
}
问题1:僵尸进程
原因:
wait()
或waitpid()
等待子进程结束。解决方法:
wait()
或waitpid()
。问题2:等待超时
原因:
waitpid()
时设置了WNOHANG
选项,但子进程尚未结束。解决方法:
while (waitpid(pid, &status, WNOHANG) == 0) {
printf("Parent process: Waiting for child...\n");
sleep(1);
}
通过以上方法和示例代码,可以有效管理和控制Linux系统中的父子进程关系,确保系统的稳定性和资源的合理利用。
领取专属 10元无门槛券
手把手带您无忧上云