进程中的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、子进程的退出状态,由传入的参数决定,所以这样可以作为一个判断,进而做进一步的处理。

猜你喜欢

转载自blog.csdn.net/zxy131072/article/details/89477344
今日推荐