《Unix环境高级编程》:演示不同的exit值

来源:互联网 发布:网络爬虫软件排名 编辑:程序博客网 时间:2024/05/22 23:39

《Unix环境高级编程》这本书附带了许多短小精美的小程序,我在阅读此书的时候,将书上的代码按照自己的理解重写了一遍(大部分是抄书上的),加深一下自己的理解(纯看书太困了,呵呵)。此例子在Ubuntu10.04上测试通过。


程序简介:这个程序演示了不同的EXIT值,并打印出相关信息


//《APUE》程序8-3:打印exit状态说明//《APUE》程序8-4:演示不同的exit值#include <sys/wait.h>#include <stdio.h>#include <stdlib.h>void pr_exit(int status);void error_quit(const char *str);int main(void){pid_t pid;int status;pid = fork();if( pid < 0 )error_quit("fork error");//子线程直接退出else if( pid == 0 )exit(7);if( wait(&status) != pid )error_quit("wait error");pr_exit(status);pid = fork();if( pid < 0 )error_quit("fork error");//产生SIGART信号else if( pid == 0 )abort();//等待子进程退出if( wait(&status) != pid )error_quit("wait error");pr_exit(status);pid = fork();if( pid < 0 )error_quit("fork error");//除数为0,产生SIGFPE信号else if( pid == 0 )status /= 0;//等待子进程退出if( wait(&status) != pid )error_quit("wait error");pr_exit(status);return 0;}//输出错误信息并退出void error_quit(const char *str){fprintf(stderr, "%s\n", str);exit(1);}void pr_exit(int status){if( WIFEXITED(status) ){printf("normal termination, exit status = %d\n", WEXITSTATUS(status));}else if( WIFSIGNALED(status) ){printf("abnormal termination, signal number = %d%s\n", WTERMSIG(status),#ifdef WCOREDUMP//no的输出是我加上去的//这里不知为什么,输出的结果和书上说的不一样WCOREDUMP(status) ? " (core file gererated)" : " no ");#else"");#endif}else if( WIFSTOPPED(status) ){printf("child stopped, signal number = %d\n", WSTOPSIG(status));}}


运行示例(红色字体的为输入):

qch@ubuntu:~/code$gcc temp.c -o temp
temp.c: In function ‘main’:
temp.c:43: warning: division by zero
qch@ubuntu:~/code$ ./temp
normal termination, exit status = 7
abnormal termination, signal number = 6 no 
abnormal termination, signal number = 8 no 


注意:不知为什么在我的电脑上,WCOREDUMP宏的返回结果与书上说的不一样,这个问题以后要研究一下。