方林

再多的天才也无法胜过对细节的关注
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

linux wait()和waitpid()简要分析理解

Posted on 2012-05-17 15:49  fl_dream  阅读(768)  评论(0编辑  收藏  举报

一.思维导图
    

 

二.实例讲解
 1.wait()

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

int main()
{
  pid_t pc, pr; 
  pc = fork();
  if(pc<0){
    printf("fork error\n");
  }else if(pc == 0){ 
    printf("this is child process.\n");
  }else{
    sleep(20);
    printf("this is parent process.\n");
  }

  exit(0);
}

[fl@linux1 c]$./wait

[fl@linux1 c]$ ps aux|grep wait
fl 8326 0.0 0.0 1600 276 pts/6 S+ 13:52 0:00 ./wait
fl 8327 0.0 0.0 0 0 pts/6 Z+ 13:52 0:00 [wait] <defunct>
fl 8330 2.0 0.0 4012 672 pts/5 R+ 13:52 0:00 grep wait
可以看出父进程sleep(20),没有调用wait()等待子进程终止,子进程就出会现运行结束无父进程清理自己的现象,从而成为Zombine进程.
如果在sleep(20)调用wait(NULL),运行结果就不会出现zombine进程。
fork()与wait()通常会配套使用。

2.waitpid()
   waitpid的原型是pid_t waitpid(pid_t pid, int *status, int options),本质上waitpid只是wait的封装
   参数pid的值有三种类型:
  pid>0,表示只等待进程ID等于pid的子进程
  pid=-1,等待任何一个子进程退出,此时于wait的作用无区别
  pid<-1,等待一个指定的进程组中的任何子进程,这个进程组的id等到于pid的绝对值。