/* [<][>][^][v][top][bottom][index][help] */
DEFINITIONS
This source file includes following definitions.
- dofork
- dowait
- main
1 /*
2 * widefork - parent process forks several children. Children do not fork.
3 *
4 * relies only on fork, console write, and _exit
5 * also uses getpid and waitpid, but will work (though differently) if they are
6 * not fully implemented
7 *
8 * parent prints creates three children, printing "P" before each fork.
9 * children print their name (A, B, or C), then exit with unique return code.
10 * parent waits for children in birth order, prints lower case child name
11 * (a, b, or c) if return value from waitpid is correct. Parent prints
12 * x instead of child name if return value is not correct.
13 *
14 * Example of correct output: PAPBPCabc
15 *
16 */
17 #include <unistd.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <err.h>
21
22 int dofork(int);
23 void dowait(int,int);
24
25 int
26 dofork(int childnum)
27 {
28 pid_t pid;
29 pid = fork();
30 if (pid < 0) {
31 errx(1,"fork %d",childnum);
32 }
33 else if (pid == 0) {
34 /* child */
35 putchar('A'+childnum-1);
36 putchar('\n');
37 _exit(childnum);
38 }
39 return(pid);
40 }
41
42 void
43 dowait(int childpid, int childnum)
44 {
45 int rval;
46 if (waitpid(childpid,&rval,0) < 0) {
47 warnx("waitpid 1");
48 return;
49 }
50 if (WIFEXITED(rval)) {
51 if ((WEXITSTATUS(rval)) == childnum) {
52 putchar('a'+childnum-1);
53 putchar('\n');
54 }
55 }
56 else {
57 putchar('x');
58 putchar('\n');
59 }
60 }
61
62 int
63 main(int argc, char *argv[])
64 {
65 (void)argc;
66 (void)argv;
67 pid_t pid1,pid2,pid3;
68 putchar('P');
69 putchar('\n');
70 pid1 = dofork(1);
71 putchar('P');
72 putchar('\n');
73 pid2 = dofork(2);
74 putchar('P');
75 putchar('\n');
76 pid3 = dofork(3);
77 dowait(pid1,1);
78 dowait(pid2,2);
79 dowait(pid3,3);
80 return(0);
81 }