请注意,虽然名字一样,这里的参数status并不同于wait唯一的参数--指向整数的指针status,而是那个指针所指向的整数,切记不要搞混了。)
● WEXITSTATUS(status)
当WIFEXITED返回非零值时,我们可以用这个宏来提取子进程的返回值,如果子进程调用exit(5)退出,WEXITSTATUS(status)就会返回5;如果子进程调用exit(7),WEXITSTATUS(status)就会返回7。请注意,如果进程不是正常退出的,也就是说,WIFEXITED返回0,这个值就毫无意义。
下面通过例子来实战一下我们刚刚学到的内容:
/* wait2.c */ #include #include #include main() { int status; pid_t pc,pr; pc=fork(); if(pc<0) /* 如果出错 */ printf("error ocurred!n"); else if(pc==0){ /* 子进程 */ printf("This is child process with pid of %d.n",getpid()); exit(3); /* 子进程返回3 */ } else{ /* 父进程 */ pr=wait(&status);
if(WIFEXITED(status)){ /* 如果WIFEXITED返回非零值 */ printf("the child process %d exit normally.n",pr); printf("the return code is %d.n",WEXITSTATUS(status)); }else /* 如果WIFEXITED返回零 */ printf("the child process %d exit abnormally.n",pr); }
} |
编译并运行:
$ cc wait2.c -o wait2 $ ./wait2 This is child process with pid of 1538. the child process 1538 exit normally. the return code is 3. |
父进程准确捕捉到了子进程的返回值3,并把它打印了出来。
当然,处理进程退出状态的宏并不止这两个,但它们当中的绝大部分在平时的编程(www.cppentry.com)中很少用到,就也不在这里浪费篇幅介绍了,有兴趣的读者可以自己参阅Linu |