fork.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * fork test for uClibc
  4. *
  5. * Copyright (C) 1999,2000 by Lineo, inc. Written by Erik Andersen
  6. * <andersen@lineo.com>, <andersee@debian.org>
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU Library General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or (at your
  11. * option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful, but WITHOUT
  14. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  15. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
  16. * for more details.
  17. *
  18. * You should have received a copy of the GNU Library General Public License
  19. * along with this program; if not, write to the Free Software Foundation,
  20. * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  21. *
  22. */
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <unistd.h>
  26. #include <sys/wait.h>
  27. #define GOT1 (1 << 1)
  28. #define GOT2 (1 << 2)
  29. #define GOT3 (1 << 3)
  30. void child_handler(int sig)
  31. {
  32. fprintf(stderr, "I got a SIGCHLD\n");
  33. }
  34. int main(void)
  35. {
  36. pid_t pid1, pid2, pid3;
  37. int status, result, wpid;
  38. signal(SIGCHLD, child_handler);
  39. if ((pid1 = fork()) == 0) {
  40. fprintf(stderr, "The child process sleeps 2 seconds...\n");
  41. sleep(4);
  42. fprintf(stderr, "Child exiting.\n");
  43. exit(-1);
  44. }
  45. if ((pid2 = fork()) == 0) {
  46. fprintf(stderr, "The child process sleeps 3 seconds...\n");
  47. sleep(3);
  48. fprintf(stderr, "Child exiting.\n");
  49. exit(-1);
  50. }
  51. if ((pid3 = fork()) == 0) {
  52. fprintf(stderr, "The child process sleeps 4 seconds...\n");
  53. sleep(2);
  54. fprintf(stderr, "Child exiting.\n");
  55. exit(-1);
  56. }
  57. fprintf(stderr, "Parent: waiting for the child to die.\n");
  58. status = 0;
  59. while (1) {
  60. wpid = waitpid(pid1, &result, WNOHANG);
  61. if (wpid == pid1)
  62. status |= GOT1;
  63. wpid = waitpid(pid2, &result, WNOHANG);
  64. if (wpid == pid2)
  65. status |= GOT2;
  66. wpid = waitpid(pid3, &result, WNOHANG);
  67. if (wpid == pid3)
  68. status |= GOT3;
  69. if (status == (GOT1 | GOT2 | GOT3))
  70. break;
  71. }
  72. fprintf(stderr, "Child process exited.\nGoodbye.\n");
  73. return EXIT_SUCCESS;
  74. }
  75. /*
  76. Local Variables:
  77. c-file-style: "linux"
  78. c-basic-offset: 4
  79. tab-width: 4
  80. End:
  81. */