1 /* 2 * Copyright 2007, Axel Dörfler, axeld@pinc-software.de. All rights reserved. 3 * Distributed under the terms of the MIT License. 4 */ 5 6 7 #include <errno.h> 8 #include <inttypes.h> 9 #include <stdio.h> 10 #include <string.h> 11 #include <sys/resource.h> 12 #define _BSD_SOURCE 13 #include <sys/wait.h> 14 #include <unistd.h> 15 16 17 /*! 18 wait() should wait only once. If any argument is given, waitpid() should return 19 an error (and errno to ECHILD), since there is no child with that process group ID. 20 */ 21 22 23 int 24 child2() 25 { 26 sleep(2); 27 return 2; 28 } 29 30 31 //! exits before child 2 32 int 33 child1() 34 { 35 setpgrp(); 36 // put us into a new process group 37 38 pid_t child = fork(); 39 if (child == 0) 40 return child2(); 41 42 sleep(1); 43 return 1; 44 } 45 46 47 int 48 main(int argc, char** argv) 49 { 50 bool waitForGroup = argc > 1; 51 52 pid_t child = fork(); 53 if (child == 0) 54 return child1(); 55 56 struct rusage usage; 57 pid_t pid; 58 do { 59 memset(&usage, 0, sizeof(usage)); 60 int childStatus = -1; 61 pid = wait4(-1, &childStatus, 0, &usage); 62 printf("wait4() returned %" PRId32 " (%s), child status %" PRId32 63 ", kernel: %ld.%06" PRId32 " user: %ld.%06" PRId32 "\n", 64 pid, strerror(errno), childStatus, usage.ru_stime.tv_sec, 65 usage.ru_stime.tv_usec, usage.ru_utime.tv_sec, 66 usage.ru_utime.tv_usec); 67 } while (pid >= 0); 68 69 return 0; 70 } 71 72