废话不多说开代码
在父进程调用wait()
#include<stdio.h> #include<unistd.h> #include<sys/wait.h> int main(int argc,char *argv[]){ int rc=fork(); if(rc==0){ printf("i am child pid=%d\n",(int)getpid()); }else{ int wc=wait(NULL); printf("i am father wc=%d",wc); } return 0; } [root@localhost codec5]# ./t5 i am child pid=3243 i am father wc=3243[root@localhost codec5]# cat t5.c
在父进程调用 成功返回子进程的id号
#include<stdio.h> #include<unistd.h> #include<sys/wait.h> int main(int argc,char *argv[]){ /*int rc=fork(); if(rc==0){ printf("i am child pid=%d\n",(int)getpid()); }else{ */ int wc=wait(NULL); printf("i am father wc=%d",wc); return 0; } [root@localhost codec5]# ./t5 i am father wc=-1
在父进程调用 wait 失败返回 -1
在子进程里调用wait()
由于子进程并没有创建再创建子进程所以返回值是-1
#include<stdio.h> #include<unistd.h> #include<sys/wait.h> int main(int argc,char *argv[]){ int rc=fork(); if(rc==0){ int wc=wait(NULL); printf("i am child pid=%d,wc=%d\n",(int)getpid(),wc); }else{ printf("i am father "); } return 0; } [root@localhost codec5]# ./t5 i am father [root@localhost codec5]# i am child pid=3337,wc=-1