Linux基础学习—wait函数

头文件

#include<sys/types.h>
#include<sys/wait.h>
函数原型
pid_t wait (int * status);

参数 status 是一个整形指针。如果status不是一个空指针,则终止进程的终止状态将存储在该指针所指向的内存单元中。如果不关心终止状态,可以将 status参数设置为NULL。
调用 wait 函数时,调用进程将会出现下面的情况:

  1. 如果其所有子进程都还在运行,则阻塞。
  2. 如果一个子进程已经终止,正等待父进程获取其终止状态,则获取该子进程的终止状态然后立即返回。
  3. 如果没有任何子进程,则立即出错返回

2. 代码测试

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


int main()
{
	pid_t pid;
	int status,i;
	int cnt = 0;
	pid = fork();

	if(pid > 0){
		wait(&status);
		i=WEXITSTATUS(status);
		printf("child pid =%d ,exit status=%d\n",getpid(),i);
		while(1){
			printf("cnt: %d",cnt);
			printf("This is the parent print,pid:%d\n",getpid());
			sleep(1);
		}
	}else if(pid == 0){
		while(1){
			printf("This is the child print,pid =%d\n",getpid());
			sleep(1);	
			cnt++;
			printf("cnt: %d",cnt);
			if(cnt == 5){
				exit(5);
			}
		}

	}
	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值