[Linux] 进程管理之进程等待

1)进程等待相关概念

  • 什么是?父进程通过等待的方式,回收子进程资源,获取子进程的退出信息;
  • 为什么?防止子进程发生僵尸问题,回收子进程资源,避免内存泄漏;获取子进程退出时的退出信息;
  • 怎么做?通过使用wait( )、waitpid( )函数进行系统调用。

2)pid_t wait(int* status)

  • wait成功返回所等待子进程的pid,失败返回-1,表示子进程还没有退出;等待方式默认为阻塞式等待。

3)pid_t waitpid(pid_t pid, int* status, int option)

  • pid可取值为任意子进程的pid,当其取值为-1时,表示等待任意一个子进程;
  • 关于status:
    1. status是一个输出型参数,子进程退出后,操作系统会从PCB中读取子进程的退出信息,保存在status所指向的变量中;
    2. 当其值为NULL时,表示等待的时候并不关心子进程的退出状态;
    3. status可以看做是一个位图,我们一般只看它的低16位,其中次低8位表示进程退出时的退出状态(正常退出),低7位表示 终止信号(被信号杀死);
    4. 相关图示如下:
      status
    5. option取值为0时,表示以阻塞的方式进行等待;取值为WNOHANG时,表示以非阻塞的方式进行等待,当其以非阻塞方式等待时,函数返回值为0表示子进程还没有退出,返回值大于0表示子进程退出了;
    6. (status&0x7f)0:表示正常退出,(status>>8)&0xff0:表示异常退出
    7. 当然,操作系统中也有相应的宏让我们去使用:
      WIFEXITED(status)---- 判断子进程是否正常退出,若进程是正常终止,则返回真;
      WEXITSTATUS(status)---- 获取子进程的退出码。

4)测试代码----以阻塞方式进行等待

int main(){
printf("begin start...\n");
pid_t id = fork();  //fork()之后,父子进程代码共享,数据各自私有
if(id == 0){ //child
	int count = 0;
	while(count<5){
		printf("child %d is running...\n", getpid());
		sleep(1);
		count++;
	}
	exit(10);
}
else if(id > 0){ //father
	int status = 0;
	//pid_t ret = wait(&status);
	pid_t ret = waitpid(id, &status, 0);  //0表示以阻塞的方式等待
	if(WIFEXITED(status)){  //调用系统函数判断是否是正常退出
		printf("ret: %d\n", ret);
		printf("child exit code: %d\n", WEXITSTATUS(status));  //提取正常退出的退出码
		printf("child exit code: %d\n", (status>>8)&0xff);
		printf("father wait end...\n");
	}
	else if(ret>0){  //子进程退出了,但是为异常退出
		printf("status: %d\n", status);
		printf("child exit code: %d\n", (status)&0x7f);  //获取终止信号
		printf("father wait end...\n");
	}
	else{
		printf("wait failed...\n");
	}
}
else{ //error
	printf("error......");
}
}

5)测试代码----以非阻塞方式进行等待

int main(){
printf("begin start...\n");

pid_t id = fork();
//fork()之后,父子进程代码共享,数据各自私有
if(id == 0){ //child
	int count = 0;
	while(count<5){
		printf("child %d is run\n", getpid());
		sleep(1);
		count++;
	}
	exit(10);
}

else if(id > 0){ //father
	int status = 0;
	pid_t ret = 0;
	do{
		ret = waitpid(id, &status, WNOHANG);  //WNOHANG表示以非阻塞的方式等待
		if(ret==0){
			printf("child is running...\n");
		}
		sleep(2);
	}while(ret==0); //ret为0表示当前子进程还没有退出,ret>0表示当前子进程退出了

	if(WIFEXITED(status)){  //调用系统函数判断是否是正常退出
			printf("status: %d\n", status);
			printf("child exit code: %d\n", WEXITSTATUS(status));  //提取正常退出的退出码
			printf("father wait end...\n");
	}
	else{
		printf("wait failed...\n");  //异常退出
	}
}
else{ //error
	printf("error......");
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值