os161-1.99
 All Data Structures
widefork.c
00001 /*
00002  * widefork - parent process forks several children.  Children do not fork.
00003  *
00004  *  relies only on fork, console write, and _exit
00005  *  also uses getpid and waitpid, but will work (though differently) if they are
00006  *   not fully implemented
00007  *
00008  *  parent prints creates three children, printing "P" before each fork.
00009  *  children print their name (A, B, or C), then exit with unique return code.
00010  *  parent waits for children in birth order, prints lower case child name
00011  *  (a, b, or c) if return value from waitpid is correct.   Parent prints
00012  *  x instead of child name if return value is not correct.
00013  *
00014  *  Example of correct output:  PAPBPCabc
00015  *
00016  */
00017 #include <unistd.h>
00018 #include <stdlib.h>
00019 #include <stdio.h>
00020 #include <err.h>
00021 
00022 int dofork(int);
00023 void dowait(int,int);
00024 
00025 int
00026 dofork(int childnum) 
00027 {
00028   pid_t pid;
00029   pid = fork();
00030   if (pid < 0) {
00031     errx(1,"fork %d",childnum);
00032   }
00033   else if (pid == 0) {
00034     /* child */
00035     putchar('A'+childnum-1);
00036     putchar('\n');
00037     _exit(childnum);
00038   }
00039   return(pid);
00040 }
00041 
00042 void
00043 dowait(int childpid, int childnum)
00044 {
00045   int rval;
00046   if (waitpid(childpid,&rval,0) < 0) {
00047     warnx("waitpid 1");
00048     return;
00049   }
00050   if (WIFEXITED(rval)) {
00051     if ((WEXITSTATUS(rval)) == childnum) {
00052       putchar('a'+childnum-1);
00053       putchar('\n');
00054     }
00055   }
00056   else {
00057     putchar('x');
00058     putchar('\n');
00059   }
00060 }
00061 
00062 int
00063 main(int argc, char *argv[])
00064 {
00065   (void)argc;
00066   (void)argv;
00067   pid_t pid1,pid2,pid3;
00068   putchar('P');
00069   putchar('\n');
00070   pid1 = dofork(1);
00071   putchar('P');
00072   putchar('\n');
00073   pid2 = dofork(2);
00074   putchar('P');
00075   putchar('\n');
00076   pid3 = dofork(3);
00077   dowait(pid1,1);
00078   dowait(pid2,2);
00079   dowait(pid3,3);
00080   return(0);
00081 }
 All Data Structures