进程等待

来源:互联网 发布:win7怎么自动连接网络 编辑:程序博客网 时间:2024/06/09 16:58
进程等待:
(一)
pid-t wait(int* status);
参数:status为一个输出型参数,用于获得所等待进程的退出信息;
返回值:成功返回的是所等待进程的pid,大于0。
             失败返回-1.
(二)
pid_t waitpid(pid_t pid,int* status,int options) ;
参数:
pid 为所等待进程的pid;
status:所等待进程的退出信息;
option:设定等待的方式;
option = 0:   阻塞式等待
option = WNOHANG:  非阻塞式等待。
(三)
进程的异步等待:
父进程可以通过 wait 和waitpid函数对于子进程进行等待,可以以阻塞的方式等待,,也可以以非阻塞(轮询)的方式进行。但是这都会影响父进程的运行。

SIGCHLD信号:
子进程退出时会给父进程,发送SIGCHILD信号,父进程对于这种信号的操作为忽略,我们可以通过捕捉该信号,当子进程给父进程发送SIGCHILD时,父进程再去回收就可以了。

编写代码验证子进程退出时确实会给父进程发送SIGCHILD信号
#include<stdio.h>#include<signal.h>#include<sys/types.h>#include<unistd.h>void myhandler(){    printf("I get the SEMCHILD.\n");}int main(){    //捕捉SIGCHILD信号    struct sigaction act,oact;    act.sa_handler = myhandler;    sigemptyset(&act.sa_mask);    act.sa_flags = 0;    sigaction(SIGCHLD,&act,&oact);        //子进程    int i = 0;    pid_t id = fork();    if(id == 0)    {        //child        printf("pid = %d,ppid = %d\n",getpid(),getppid());        exit(1);    }    while(1)    {        sleep(1);        ++i;        printf("  I am the parent process.%d\n",getpid());    }    return 0;}
运行结果:

父进程对于子进程进行异步等待:
       确定了子进程退出时会给父进程发送SIGCHLD信号,父进程就不用以阻塞的或非阻塞(轮询)的方式,对于子进程进行等待;
父进程可以对于SIGCHLD进行捕捉,当有这个信号发来的时候进行处理就可以了。
#include<stdio.h>#include<sys/types.h>#include<sys/wait.h>#include<unistd.h>#include<signal.h>#include<stdlib.h>static pro_num = 0;void myhandler(){    pro_num++;    pid_t wpid = waitpid(-1,NULL,WNOHANG);    if(wpid > 0)    {        printf("the %d process is wait success.\n",pro_num);    }    else    {        printf("the %d process is wait failed.\n",pro_num);    }}int main(){    //信号捕捉    struct sigaction act,oact;    act.sa_handler = myhandler;    sigemptyset(&act.sa_mask);    act.sa_flags = 0;    sigaction(SIGCHLD,&act,&oact);    //创建子进程    pid_t pid1 = fork();    if(pid1 == 0)    {        exit(1);    }    pid_t pid2 = fork();    if(pid2 == 0)    {        sleep(1);        exit(1);    }    pid_t pid3 = fork();    if(pid3 == 0)    {        sleep(2);        exit(1);    }    pid_t pid4 = fork();    if(pid4 == 0)    {        sleep(10);        exit(1);    }    while(1)    {}    return 0;}
运行结果:
 



好了,就说这么多,以后大家要进程等待就有三种方法啦。微笑
作者水平有限,若有问题,请留言,谢谢!!!


原创粉丝点击