进程中的wait函数

wait函数

 pid_t wait(int *status);

功能:
		阻塞并等待子进程退出 
	    回收子进程残留资源 
		获取子进程结束状态(退出原因)
返回值:
	成功:清理掉的子进程ID
	失败:-1 (没有子进程)
	
参数:子进程的退出状态 -- 传出参数
	1.	WIFEXITED(status):为非0	→ 进程正常结束
			WEXITSTATUS(status):
			如上宏为真,使用此宏 → 获取进程退出状态 (exit/return)的参数)
	2.	WIFSIGNALED(status):为非0 → 进程异常终止
			WTERMSIG(status):
			如上宏为真,使用此宏 → 取得使进程终止的那个信号的编号。

测试源码

 #include <stdio.h>
 #include <unistd.h>
 #include <stdlib.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <string.h>
 #include <sys/wait.h>
 
 int counter = 200;
 
 int main(int argc, const char* argv[])
 {
     int i;
     pid_t pid;
     for(i=0; i<5; ++i)
     {
         //只是使用父进程创建新的进程,将子进程直接干掉,一共创建了5个子进程
         pid = fork();
         if(pid == 0)
         {
             break;
         }
     }
 
     if(i<5)
     {                                                                                                                                                                                                                             
       counter += 300;
       printf(" child process , pid = %d,  ppid = %d\n", getpid(), getppid());
       printf("counter = %d\n\n", counter);
   }
   //为父进程
   else if(i == 5)
   {
       counter += 100;
       printf(" parent process, pid = %d, ppid = %d\n", getpid(), getppid());
       printf("counter = %d\n\n", counter);
       sleep(1);

       // 父进程, 回收子进程资源
       int status;
       pid_t wpid;
       while((wpid = wait(&status)) != -1 )
       {
           printf("child process died, pid = %d\n", wpid);
           if(WIFEXITED(status))
           {
               printf("process exit value: %d\n", WEXITSTATUS(status));
           }
           else if(WIFSIGNALED(status))
           {
               printf("process exit by signal: %d\n", WTERMSIG(status));
           }
         }
     }
 }    

测试结果:

在这里插入图片描述

关键代码分析

1、父子进程之间,对于counter,创建了不同的用户空间,所以每一个进程之间counter的初始值均为200。
2、wait函数会等待子进程执行完毕后父进程再退出。
3、子进程的退出状态,由传入的参数决定,所以这样可以作为一个判断,进而做进一步的处理。
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值