wait与waitpid详解

来源:互联网 发布:照片软件 编辑:程序博客网 时间:2024/06/14 12:34




                本问结合UNP以及在网上搜集的资料,整理除了关于wait和waitpid的一些区别,

先看一段代码:

                   

#include <unistd.h>#include <dirent.h>#include <stdio.h>#include <sys/wait.h>int main(int argc,char**argv){pid_t child;int i;child=fork();if(child<0){printf("create failed\n");exit(1);}else if(0==child){printf("this is the child process pid=%d,parentid=%d\n",getpid(),getppid());for(i=0;i<5;i++)printf("child print hello\n");printf("the child end\n");}else{printf("this is the father proces  pid=%d\n",getpid());printf("father wait the child end\n");wait(&child);printf("father end\n");}}

执行结果如图



从中可以看出来,在父进程调用wait后,它被挂起来了,直到子进程结束后,它才被唤醒,从而wait掉子进程。


这就产生了一个问题,如果说,一个父进程同时fork()出了多个子进程,且这多个子进程同时发出了SIGCHILD的结束信号,那么,父进程这时在处理第一个接受到的

SIGCHILD信号时,它被挂起了,其他的SIGCHILD信号处理不了了,这样即导致了僵死进程的产生。



那么有什么办法可以阻止在处理SIGCHILD信号时,还能处理其他的SIGCHILD信号呢?换言之,即  在有未终止的其他子进程还在运行时候,不要阻塞父进程呢?


这就是waitpid函数,

                    int waitpid(pid_t pid,int *stalo,int options)


其中,若指定options为WNOHANG 时,它就到达了上面的功能。

这个函数比wait还有更多的控制功能,体现在pid上面,它可以等待wait特殊的指定的进程,利用pid可以指明,

若pid=-1时候,那么它受理所有发出SIGCHILD信号的子进程。


              可以利用waitpid写出信号捕获函数:

         void  sig_child(int signo)

{         

                  pid_t pid;

                   int stat;

                  while((pid=waitpid(-1,&stat,WNOHANG))>0)

                   {

                               printf(" child %d terminated\n",pid);

                   }


                 return ;

}




在while中不能使用wait函数,因为它没有WNOHANG可以指定。。。。。。。。



0 0
原创粉丝点击