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