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 <stdio.h> 9#include <string.h> 10#include <sys/wait.h> 11#include <unistd.h> 12 13 14/*! 15 wait() should wait only once. If any argument is given, waitpid() should return 16 an error (and errno to ECHILD), since there is no child with that process group ID. 17*/ 18 19 20int 21child2() 22{ 23 sleep(3); 24 return 2; 25} 26 27 28//! exits before child 2 29int 30child1() 31{ 32 pid_t child = fork(); 33 if (child == 0) 34 return child2(); 35 36 sleep(1); 37 setpgrp(); 38 // put us into a new process group 39 sleep(1); 40 return 1; 41} 42 43 44int 45main(int argc, char** argv) 46{ 47 bool waitForGroup = argc > 1; 48 49 pid_t child = fork(); 50 if (child == 0) 51 return child1(); 52 53 pid_t pid; 54 do { 55 int childStatus = -1; 56 if (waitForGroup) 57 pid = waitpid(0, &childStatus, 0); 58 else 59 pid = wait(&childStatus); 60 printf("wait() returned %ld (%s), child status %d\n", 61 pid, strerror(errno), childStatus); 62 } while (pid >= 0); 63 64 return 0; 65} 66 67