widefork.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. int dofork(int);
  22. void dowait(int,int);
  23. int
  24. dofork(int childnum)
  25. {
  26. pid_t pid;
  27. pid = fork();
  28. if (pid < 0) {
  29. errx(1,"fork %d",childnum);
  30. }
  31. else if (pid == 0) {
  32. /* child */
  33. putchar('A'+childnum-1);
  34. putchar('\n');
  35. _exit(childnum);
  36. }
  37. return(pid);
  38. }
  39. void
  40. dowait(int childpid, int childnum)
  41. {
  42. int rval;
  43. if (waitpid(childpid,&rval,0) < 0) {
  44. warnx("waitpid 1");
  45. return;
  46. }
  47. if (WIFEXITED(rval)) {
  48. if ((WEXITSTATUS(rval)) == childnum) {
  49. putchar('a'+childnum-1);
  50. putchar('\n');
  51. }
  52. }
  53. else {
  54. putchar('x');
  55. putchar('\n');
  56. }
  57. }
  58. int
  59. main(int argc, char *argv[])
  60. {
  61. (void)argc;
  62. (void)argv;
  63. pid_t pid1,pid2,pid3;
  64. putchar('P');
  65. putchar('\n');
  66. pid1 = dofork(1);
  67. putchar('P');
  68. putchar('\n');
  69. pid2 = dofork(2);
  70. putchar('P');
  71. putchar('\n');
  72. pid3 = dofork(3);
  73. dowait(pid1,1);
  74. dowait(pid2,2);
  75. dowait(pid3,3);
  76. return(0);
  77. }