一、wait
wait 函数 :阻塞函数,使进程一直处于等待状态,直至进程死亡。
(1)头文件:
#include <sys/types.h>
#include <sys/wait.h>
(2)函数使用:
pid_t wait(int *status);
参数用于判断子进程的死亡原因。
正常死亡:return 0 exit(1)
信号杀死:kill -9 pid
详细如下代码所示:
int status; // 传出参数
pid_t wpid = wait(&status);
if(WIFEXITED(status)) // WIFEXITED(status) 非 0,说明程序正常结束
{
printf(“exit value : %d\n”, WEXITSTATUS(status)); // 结果是 return 或 exit 的值
}
else if(WIFSIGNALED(status)) // WIFSIGNALED(status) 非 0,说明程序异常终止,信号杀死
{
printf(“kill by Signal: %d\n”, WTERMSIG(status)); // 结果说明是被几号信号杀死的
}
若不关心死亡原因可简化使用方法:wait(NULL);
(3)返回值类型:pid_t
返回值 = -1 表示失败,意味着没有子进程,回收结束。
返回值 > 0 返回值是被回收子进程的 pid。
注意:wait 函数一次只能回收一个子进程,回收多个子进程需要循环(注意判断条件)
while( ( wpid = wait(&status) ) != -1) { 判断死亡原因 } // 关心死亡原因
while( ( wpid = wait(NULL) ) != -1) { } // 不关心死亡原因
二、waitpid
waitpid 函数可以设置非阻塞。
(1)函数使用:
pid_t waitpid(pid_t pid, int *status, int options);
(2)
参数 pid_t pid:
当pid=-1:回收任意一个子进程
当pid> 0:回收进程 ID 等于 pid 的子进程(定向回收)
参数 status: 用于判断死亡原因,同 wait 函数
参数 options:设置为 0表示阻塞; 设置为 WNOHANG表示非阻塞。
(3)
返回值 > 0 :被回收子进程的 pid。
返回值 =-1 :回收结束。
返回值 = 0 :设置为 WNOHANG 会出现,且还有子进程正在运行,没有退出 。
注意:waitpid 函数一次也只能回收一个子进程,回收多个子进程需要循环。代码如下:
while( ( wpid = waitpid(-1,&status, WNOHANG) ) != -1)
{
if(wpid == 0) {
continue; // 子进程还在运行,所以没必要执行下面的代码
}
printf(“child died pid = %d\n”,wpid);
if(WIFEXITED(status)) {
printf(“exit value : %d\n”, WEXITSTATUS(status));
}
else if(WIFSIGNALED(status)) {
printf(“kill by Signal: %d\n”, WTERMSIG(status));
}
}