fork.c 1013 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <errno.h>
  7. #include <unistd.h>
  8. #include <sys/wait.h>
  9. int main (int argc, const char ** argv)
  10. {
  11. pid_t pid1 = fork();
  12. if (pid1 < 0) {
  13. printf("failed on fork (%s)\n", strerror(errno));
  14. return -1;
  15. }
  16. if (pid1 == 0) {
  17. pid_t pid2 = fork();
  18. if (pid2 < 0) {
  19. printf("failed on fork (%s)\n", strerror(errno));
  20. return -1;
  21. }
  22. if (pid2 == 0) {
  23. printf("[pid=%d|ppid=%d] Hello, Grandpa!\n", getpid(), getppid());
  24. return 0;
  25. }
  26. waitpid(-1, NULL, 0);
  27. printf("[pid=%d|ppid=%d] Hello, Dad!\n", getpid(), getppid());
  28. return 0;
  29. }
  30. waitpid(-1, NULL, 0);
  31. printf("[pid=%d|ppid=%d] Hello, Kid!\n", getpid(), getppid());
  32. return 0;
  33. }