【C语言】FORK子进程的创建和回收(按顺序回收)

来源:互联网 发布:tfband知乎 编辑:程序博客网 时间:2024/05/21 06:51
/* ============================================================================ Name        : test.c Author      :  Version     : Copyright   : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */#include <csapp.h>#define N 15int main(void) {/*  fork test ================= */int status, i;pid_t pid[N],retpid;/* Parent creates N children */for(i=0;i<N;i++){if((pid[i] = fork() == 0)){  // childrenexit(100+i);}}/* Parent reaps N children in no particular order  */i = 0;while((retpid = waitpid(pid[i++],&status,0)) > 0){if(WIFEXITED(status)){printf("child %d terminated normally with exit status=%d\n",retpid,WEXITSTATUS(status));}else{printf("child %d terminated abnormally \n",retpid);}}/* the only normally termination is if there no more children  */if(errno != ECHILD)printf("waitpid error %c",'c');exit(0);return EXIT_SUCCESS;}


原创粉丝点击