00001 /* 00002 waitid example 00003 AUP2, Sec. 5.08 00004 00005 Copyright 2003 by Marc J. Rochkind. All rights reserved. 00006 May be copied only for purposes and under conditions described 00007 on the Web page www.basepath.com/aup/copyright.htm. 00008 00009 The Example Files are provided "as is," without any warranty; 00010 without even the implied warranty of merchantability or fitness 00011 for a particular purpose. The author and his publisher are not 00012 responsible for any damages, direct or incidental, resulting 00013 from the use or non-use of these Example Files. 00014 00015 The Example Files may contain defects, and some contain deliberate 00016 coding mistakes that were included for educational reasons. 00017 You are responsible for determining if and how the Example Files 00018 are to be used. 00019 00020 */ 00021 #include "defs.h" 00022 00023 #if defined(_XOPEN_UNIX) 00024 00025 void display_status(siginfo_t *infop); 00026 00027 /*[waitid-wait_and_display]*/ 00028 static bool wait_and_display(void) 00029 { 00030 siginfo_t info; 00031 00032 #if defined(LINUX) && !defined(WEXITED) 00033 #define WEXITED 0 00034 #endif 00035 ec_neg1( waitid(P_ALL, 0, &info, WEXITED) ) 00036 display_status(&info); 00037 return true; 00038 00039 EC_CLEANUP_BGN 00040 return false; 00041 EC_CLEANUP_END 00042 } 00043 00044 void display_status(siginfo_t *infop) 00045 { 00046 printf("Process %ld terminated:\n", (long)infop->si_pid); 00047 printf("\tcode = %s\n", 00048 get_macrostr("sigchld-code", infop->si_code, NULL)); 00049 if (infop->si_code == CLD_EXITED) 00050 printf("\texit value = %d\n", infop->si_status); 00051 else 00052 printf("\tsignal = %s\n", 00053 get_macrostr("signal", infop->si_status, NULL)); 00054 } 00055 00056 /*[]*/ 00057 int main(void) 00058 { 00059 pid_t pid; 00060 00061 /* Case 1: Explicit call to _exit */ 00062 if (fork() == 0) /* child */ 00063 _exit(123); 00064 /* parent */ 00065 ec_false( wait_and_display() ) 00066 00067 /* Case 2: Termination by kernel */ 00068 if (fork() == 0) { /* child */ 00069 int a, b = 0; 00070 00071 a = 1 / b; 00072 _exit(EXIT_SUCCESS); 00073 } 00074 /* parent */ 00075 ec_false( wait_and_display() ) 00076 00077 /* Case 3: External signal */ 00078 if ((pid = fork()) == 0) { /* child */ 00079 sleep(100); 00080 _exit(EXIT_SUCCESS); 00081 } 00082 /* parent */ 00083 ec_neg1( kill(pid, SIGHUP) ) 00084 ec_false( wait_and_display() ) 00085 00086 exit(EXIT_SUCCESS); 00087 00088 EC_CLEANUP_BGN 00089 exit(EXIT_FAILURE); 00090 EC_CLEANUP_END 00091 } 00092 00093 #else /* _XOPEN_UNIX */ 00094 00095 int main(void) 00096 { 00097 printf("waitid not implemented\n"); 00098 exit(EXIT_FAILURE); 00099 } 00100 00101 #endif /* _XOPEN_UNIX */