文章目录
- 进程等待
- 进程等待的必要性
- 进程等待的方法
- wait
- waitpid
- status
- 非阻塞等待
进程等待
任何子进程,在退出的情况下,一般必须要被父进程等待
进程等待的必要性
1.父进程通过等待,解决子进程退出的僵尸问题,回收系统资源。
2.获取子进程的退出信息,知道子进程是为什么退出的。
进程等待的方法
wait
pid_t wait(int*status);
如果子进程没有退出,父进程则一直进行堵塞等待。
等待成功时,返回子进程的pid。
子进程本身是软件,父进程本质是等待某种软件条件就绪。
阻塞等待:将父进程设为S状态(非运行状态),把父进程的PCB链入子进的度队列中。
waitpid
pid_t waitpid(pid_t pid,int *status,int options);
返回值:
当正常返回的时候waitpid返回收集到的子进程的进程ID;
如果设置了选项WNOHANG,而调用中waitpid发现没有已退出的子进程可收集,则返回0;
如果调用中出错,则返回-1,这时errno会被设置成相应的值以指示错误所在;
pid:
Pid=-1,等待任一个子进程。与wait等效。
Pid>0.等待其进程ID与pid相等的子进程。
status:
WIFEXITED(status): 若为正常终止子进程返回的状态,则为真。(查看进程是否是正常退出)
WEXITSTATUS(status): 若WIFEXITED非零,提取子进程退出码。(查看进程的退出码)
options:
WNOHANG: 若pid指定的子进程没有结束,则waitpid()函数返回0,不予以等待。若正常结束,则返回该子进程的ID。
如果子进程已经退出,调用wait/waitpid时,wait/waitpid会立即返回,并且释放资源,获得子进程退出信息。
如果在任意时刻调用wait/waitpid,子进程存在且正常运行,则进程可能阻塞。 如果不存在该子进程,则立即出错返回。
waitpid使用:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>void child() {int cnt = 5;while (cnt) {printf("i am child pid=%d ppid=%d cnt=%d\n", getpid(), getppid(), cnt);sleep(1);cnt--;}
}int main() {pid_t pid;int status;// 创建子进程pid = fork();if (pid < 0) {// 创建子进程失败perror("fork error\n");} else if (pid == 0) {child();} else {// 父进程代码// 等待子进程结束if (waitpid(pid, &status, 0) == -1) {perror("waitpid");exit(EXIT_FAILURE);}// 分析子进程的退出状态if (WIFEXITED(status)) {printf("Child exited normally with status %d\n",WEXITSTATUS(statu s));} else {printf("child exited abnormal\n");}// 标志位if (WCOREDUMP(status)) {printf("Child produced a core dump\n");} else {printf("Child did not produce a core dump\n");}}return 0;
}
status
wait和waitpid,都有一个status参数,该参数是一个输出型参数,由操作系统填充。
若传NULL,表示不关心子进程的退出状态。
否则,根据该参数将子进程退出信息反馈给父进程。
非阻塞等待
将waitpid的option参数设置为WNOHANG。
pid_t>0:等待成功了,子进程退出,父进程成功回收子进程退出信息。
pid_t<0,等待失败了。
pid_t==0,子进程还没有退出,需进行下一轮等待。
非阻塞等待+循环=非阻塞轮询
非阻塞轮询运行父进程在等待过程中做其他事
测试一下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>void child() {int cnt = 5;while (cnt) {printf("i am child pid=%d ppid=%d cnt=%d\n", getpid(), getppid(), cnt);sleep(1);cnt--;}
}int main() {pid_t pid;int status;// 创建子进程pid = fork();if (pid < 0) {// 创建子进程失败perror("fork error\n");} else if (pid == 0) {child();}while (1) {pid_t rid = waitpid(pid, &status, WNOHANG);if (rid == 0) {usleep(10000);printf("child is running,father check next time!\n");printf("doing other thing\n");} else if (rid > 0) {if (WIFEXITED(status)) {printf("child quit success,child exit code:%d\n",WEXITSTATUS(status));} else {printf("child quit abnormal\n");}break;}}return 0;
}
实际运用中将doing other things换成其他程序或函数即可。