首页 > 代码库 > 程序清单8-3 8-4 演示不同的exit值

程序清单8-3 8-4 演示不同的exit值

 1 //http://blog.chinaunix.net/uid-24549279-id-71355.html
 2 /*
 3  ============================================================================
 4  Name        : test.c
 5  Author      : blank
 6  Version     :
 7  Copyright   : Your copyright notice
 8  Description : 程序清单8-3 8-4 演示不同的exit值
 9  ============================================================================
10 */
11 
12 #include "ourhdr.h"
13 #include <sys/wait.h>
14 
15 static void pr_exit(int status);
16 
17 int main(int argc, char *argv[])
18 {
19     pid_t    pid;
20     int        status;
21 
22     if ((pid = fork()) < 0){
23         err_sys("fork error");
24     }else if(pid == 0){
25         //child
26         exit(7);
27     }
28 
29     /*
30      * wait for child and print its status
31      */
32     if (wait(&status) != pid){
33         err_sys("wait error");
34     }
35 
36     pr_exit(status);
37 
38     /*
39      * child generates SIGABRT
40      */
41     if ((pid = fork()) < 0){
42         err_sys("fork_error");
43     }else if (pid == 0){
44         abort();
45     }
46 
47     /*
48      * wait for child and print its status
49      */
50     if (wait(&status) != pid){
51         err_sys("wait error");
52     }
53 
54     pr_exit(status);
55 
56     if ((pid = fork()) < 0){
57         err_sys("fork error");
58     }else if(pid == 0){
59         // child divide by 0 generates SIGFPE
60         status/=0;
61     }
62 
63     /*
64      * wait for child and print its status
65      */
66     if (wait(&status) != pid){
67         err_sys("wait error");
68     }
69 
70     pr_exit(status);
71 }
72 
73 static void pr_exit(int status)
74 {
75     if (WIFEXITED(status)){
76         printf("normal termination, exit status = %d\n", WEXITSTATUS(status));
77     }else if (WIFSIGNALED(status)){
78         printf("abnormal termination, signal number=%d%s\n", WTERMSIG(status),
79 #ifdef WCOREDUMP
80         WCOREDUMP(status) ? " (core file generated )" : "");
81 #else
82         "");
83 #endif
84     }else if(WIFSTOPPED(status)){
85             printf("child stopped, signal number=%d\n", WSTOPSIG(status));
86         }
87 }