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):
如上宏为真,使用此宏,取得使进程终止的那个信号的编号
调用一次只能回收一个子进程
实例
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc,char *argv[])
{
pid_t fpid;
int num = 0;
num++;
printf("num is %d\n",num);
fpid = fork();
// fathere process
if(fpid > 0)
{ int status;
pid_t wpid;
wpid=wait(&status);
printf("wpid is %d\n",wpid);
//nomal exit
if(WIFEXITED(status))//如果子进程为正常退出
{
printf("exti value is %d\n",WEXITSTATUS(status));//打印出子进程退出的返回值
}
else if(WIFSIGNALED(status)) //如果为异常退出
{
printf("exti by signal is%d\n",WTERMSIG(status));//打印出取得使进程终止的那个信号的编号
}
printf("This is father process,my process pid is %d\n",getpid());
num++;
}
else if(fpid ==0)
{
while(1)
{
sleep(1);
printf("child pid is %d ,ppid is %d\n",getpid(),getppid());
}
}
printf("num is %d\n",num);
return 9;
}
~
父进程被wait函数挂起,子进程进行while(1)循环,子进程一直在运行,用kill来杀死子进程。然后父进程释放子进程的pcb数据,然后父进程再开始执行。
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 <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc,char *argv[])
{
pid_t fpid;
int num = 0;
num++;
printf("num is %d\n",num);
fpid = fork();
// fathere process
if(fpid > 0)
{ int status;
pid_t wpid;
while (( wpid = waitpid( -1, &status,0)) != -1)
{
if(wpid ==0)
{
continue;
}
printf("died process pid is %d\n",wpid);
if(WIFEXITED(status))
{
printf("exit value is %d\n",WEXITSTATUS(status));
}
if(WIFSIGNALED(status))
{
printf("exit by signal is %d\n",WTERMSIG(status));
}
}
printf("This is father process,my process pid is %d\n",getpid());
num++;
}
else if(fpid ==0)
{
//while(1)
//{
sleep(1);
printf("child pid is %d ,ppid is %d\n",getpid(),getppid());
// }
}
printf("num is %d\n",num);
return 9;
}