wait 阻塞函数
函数作用:
1. 阻塞并等待子进程退出
2. 回收子进程残留资源
3. 获取子进程结束状态(退出原因)
pid_t wait(int *wstatus);
返回值:
‐1 : 回收失败,已经没有子进程了
>0 : 回收子进程对应的 pid
参数 :
status 判断子进程如何退出状态
1.WIFEXITED(status): 为非 0 ,进程正常结束
返回WEXITSTATUS(status)
如上宏为真,使用此宏,获取进程退出状态的参数
2.WIFSIGNALED(status): 为非 0 ,进程异常退出
WTERMSIG(status):
如上宏为真,使用此宏,取得使进程种植的那个信号的编号
调用一次只能回收一个子进程
waitpid 函数
函数作用:同 wait 函数
pid_t waitpid(pid_t pid, int *status, int options);
参数
1.pid: 指定回收某个子进程
pid == ‐1 回收所有子进程
while( (wpid=waitpid(‐1,status,0)) != ‐1)
pid > 0 回收某个 pid 相等的子进程
pid == 0 回收当前进程组的任一子进程
pid < 0 子进程的 PID 取反(加减号)
2.status: 子进程的退出状态,用法同 wait 函数
3.options: 设置为 WNOHANG, 函数非阻塞,设置为 0 ,函数阻塞
返回值:
>0 : 返回清理掉的子进程 ID
‐1 :回收失败,无子进程
如果为非阻塞
=0 :参数 3 为 WNOHANG, 且子进程正在运行
#include <sys/types.h>
#include <unistd.h>
#include<stdio.h>
#include<sys/wait.h>int i=200;
int main()
{
int status;pid_t pid;
pid = fork();
if (pid>0)
{pid_t wpid;wpid=wait(&status);printf("wpid is %d\n",wpid);//nomal exit if (WIFEXITED(status)){printf("nomal exit value is %d\n",WEXITSTATUS(status));}//unnomalif(WIFSIGNALED(status)){printf("unnomal exit signal is %d\n",WTERMSIG(status));}i+=400;
printf("this is father process %d\n",getpid());printf("i=%d\n",i);
}
else if(pid==0)
{
while(1)
{sleep(1);
printf("this is child process %d,ppid is%d\n",getpid(),getppid());
printf("i=%d\n",i);
}}for(int i=0;i<3;i++)
{printf("------i=%d\n",i);
}
程序一直执行子进程
此时打开另一个终端,终止进程,返回终止进程(异常退出)的信号 9
waitpid
#include <sys/types.h>
#include <unistd.h>
#include<stdio.h>
#include<sys/wait.h>
int i=200;
int main()
{pid_t pid;
pid = fork();
if (pid>0)
{ int status;pid_t wpid;while((wpid=waitpid(-1,&status,WNOHANG))!=-1){printf("deid wpid is %d\n",wpid);//nomal exitif (WIFEXITED(status)){printf("nomal exit value is %d\n",WEXITSTATUS(status));}//unnomalif(WIFSIGNALED(status)){printf("unnomal exit signal is %d\n",WTERMSIG(status));}i+=400;
printf("this is father process %d\n",getpid());printf("i=%d\n",i);}
}
else if(pid==0)
{printf("this is child process %d,ppid is%d\n",getpid(),getppid());}for(int i=0;i<3;i++)
{printf("------i=%d\n",i);
}
return 0;
}
#include <sys/types.h>
#include <unistd.h>
#include<stdio.h>
#include<sys/wait.h>
int i=200;
int main()
{pid_t pid;
pid = fork();
if (pid>0)
{ int status;pid_t wpid;while((wpid=waitpid(-1,&status,WNOHANG))!=-1){
if(wpid==0)
{
continue;
}printf("deid wpid is %d\n",wpid);//nomal exitif (WIFEXITED(status)){printf("nomal exit value is %d\n",WEXITSTATUS(status));}//unnomalif(WIFSIGNALED(status)){printf("unnomal exit signal is %d\n",WTERMSIG(status));}i+=400;
printf("this is father process %d\n",getpid());printf("i=%d\n",i);}
}
else if(pid==0)
{printf("this is child process %d,ppid is%d\n",getpid(),getppid());}for(int i=0;i<3;i++)
{printf("------i=%d\n",i);
}
return 0;
}