fork.c 2.3 KB

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