unix环境高级编程----进程控制wait()

来源:互联网 发布:德卡斯特里奥算法 编辑:程序博客网 时间:2024/05/20 09:08

一、wait()函数

当一个进程中调用wait()函数的时候

(1)如果其所有的子程序都还在运行,则阻塞

(2)如果一个子进程已终止,则等待父进程获取其终止状态。

(3)如果没有子进程,则返回错误。


下面的实例中,在父进程中调用wait(),如果子进程还没有运行完毕,则将自己调入阻塞状态。

等待子进程运行结束后,将子进程的资源回收后,自己再运行。

#include <stdio.h>#include <unistd.h>#include <wait.h>#include <stdlib.h>int main(){   int i=0;   int j=0;   int status;   int count =0;   int a = fork();   if(a>0)      {        printf("this is parent ,pid = %d\n",getpid());        for(i= 0;i<=10;i++)        {            printf("parent is %d\n",i);            sleep(1);            wait(&status);        }//        wait(&status);      }   else     {           for(j=0;j<=10;j++)           {              printf("child is %d\n",j);              sleep(1);           }     }return 0;}



0 0
原创粉丝点击