本文主要是介绍wait函数和waitpid函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
子进程回收
回收子进程,知道子进程的死亡原因
作用:阻塞等待,回收子进程资源,查看死亡原因
pid_t wait(int *status);
status状态
返回值:成功返回终止的子进程ID,失败返回-1
子进程的死亡原因:
正常死亡WIFEXITED 如果WIFEXITED为真,使用WEXITSTATUS得到退出状态
非正常死亡WIFSIGNALED 如果WIFSIGNALED为真,使用WTERMSIG 得到信号
wait.c
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>int main(int argc,char *argv[])
{pid_t pid=fork();if(pid==0){printf("I am child,will die\n");sleep(2);while(1){printf("I am child\n");sleep(1);} //return 101;exit(102);}else if(pid>0){printf("I am parent,wait for child die\n");pid_t wpid=wait(NULL);printf("wait ok,wpid=%d,pid=%d\n",wpid,pid);if(WIFEXITED(status)){printf("child exit with %d\n",WEXITSTATUS(status));}if(WIFSIGNALED(status)){printf("child killed by %d\n",WTERMSIG(status));}while(1){sleep(1);}}return 0;
}
pid_t waitpid(pid_t pid,int *status,int options);
pid <-1 组id =-1回收任意 =0回收和调用进程组id相同组的子进程 >0回收指定ID options 0与wait相同,也会阻塞 WNOHANG如果当前没有子进程退出会立刻返回
返回值:如果设置了WNOHANG,如果没有子进程退出,返回0
如果有子进程退出,返回退出的pid
失败返回-1(没有子进程)
waitpid.c
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>int main(int argc,char *argv[])
{pid_t pid=fork();if(pid==0){printf("I am child,pid=%d\n",getpid());sleep(2);}else if(pid>0){printf("I am parent,pid=%d\n",getpid());int ret;while(ret=waitpid(-1,NULL,WNOHANG)==0){sleep(1)}printf("ret =%d\n",ret);ret=waitpid(-1,NULL,WNOHANG);if(ret<0){perror("wait arr");} while(1){sleep(1);}}return 0;
}
用wait回收多个子进程
nfork_wait.c
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>int main(int argc,char *argv[])
{int n=5;int i=0;pid_t pid;for(i=0;i<5;i++){pid=fork();if(pid==0){printf("I am child,pid=%d\n",getpid());break;}}sleep(i);if(i==5){for(i=0;i<5;i++){pid_t wpid=wait(NULL);printf("wpid=%d\n"wpid);}while(1){sleep(1);}}return 0;
}
用waitpid回收多个子进程
nfork_waitpid.c
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>int main(int argc,char *argv[])
{int n=5;int i=0;pid_t pid;for(i=0;i<5;i++){pid=fork();if(pid==0){break;}}sleep(i);if(i==5){printf("I am parent,pid=%d\n",getpid());while(1){pid_t wpid=waitpid(-1,NULL,WNONANG);if(wpid==-1){break;}else if(wpid>0){printf("waitpid wpid=%d\n",wpid);}}while(1){sleep(1);}}if(i<5){ //sleep(i); printf("I am child,pid=%d\n",getpid());}return 0;
}
这篇关于wait函数和waitpid函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!