linux之wait函数
wait函数:成功:清理掉的子进程 ID;失败:-1 (没有子进程)
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *wstatus);
wstatus是传出参数,
a.wait函数有3个功能:
(1)阻塞等待子进程退出
(2)回收子进程残留资源
(3)获取子进程结束状态(退出原因)。
b.可使用 wait 函数传出参数 status 来保存进程的退出状态。借助宏函数来进一步判断进程终止的具体原因。常用的宏函数可分为如下两组:
(1)WIFEXITED(status)为非0 -----------进程正常结束
如果宏函数WIFEXITED(status)的返回值为真(非0),则进一步调用宏函数WEXITSTATUS(status),此函数返回的是子进程退出的值,比如exit(10),返回值就是10
(2) WEXITSTATUS(status) 如上宏为真,使用此宏---------获取进程退出状态 (exit 的参数)
(3)WIFSIGNALED(status)为非0----------进程异常终止
如果宏函数WIFSIGNALED(status)的返回值为真(非0),则进一步调用宏函数WTERMSIG(status),此函数返回的是使子进程终止的那个信号的编号
(3) WTERMSIG(status) 如上宏为真,使用此宏----------取得使进程终止的那个信号的编号

wait函数的使用:wait.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
	pid_t pid,wpid;
	int status;
	pid = fork();
	if(pid==0){
		//让子进程异常退出
		execl("abnor","abnor",NULL);
		printf("---child, my parent=%d, going to sleep 3s\n",getppid());
		sleep(60);
		printf("--------------child die--------------\n");
		//exit(76);
		return 100;
	}
	else if(pid>0){
		wpid = wait(&status);//子进程的退出状态保存在status中
		if(wpid==-1){
			perror("wait error:");
			exit(1);
		}
		//子进程正常退出
		if(WIFEXITED(status)){//如果宏函数WIFEXITED(status)的返回值为真,则继续调用宏函数WEXITSTATUS(status),此函数返回的是子进程退出的值
			printf("child exit with %d\n",WEXITSTATUS(status));
		}
		
		//子进程异常退出
		//测试子进程异常退出(不是子进程自己异常):运行程序之后,新开终端 ps aux ,杀掉子进程,此时会打印 child killed by ...
		if(WIFSIGNALED(status)){
			printf("chile killed by %d\n",WTERMSIG(status));
		}
		
		while(1){
			printf("I am paraent, pid = %d, myson = %d\n",getpid(),pid);
			sleep(1);
		}
	}
	else{
		perror("fork");
		return 1;
	}

	return 0;
}

结果:
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐