fork.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 <signal.h>
  28. #include <sys/wait.h>
  29. #define GOT1 (1 << 1)
  30. #define GOT2 (1 << 2)
  31. #define GOT3 (1 << 3)
  32. void child_handler(int sig)
  33. {
  34. fprintf(stderr, "I got a SIGCHLD\n");
  35. }
  36. int main(void)
  37. {
  38. pid_t pid1, pid2, pid3;
  39. int status, result, wpid;
  40. signal(SIGCHLD, child_handler);
  41. if ((pid1 = fork()) == 0) {
  42. fprintf(stderr, "The child process sleeps 2 seconds...\n");
  43. sleep(4);
  44. fprintf(stderr, "Child exiting.\n");
  45. exit(-1);
  46. }
  47. if ((pid2 = fork()) == 0) {
  48. fprintf(stderr, "The child process sleeps 3 seconds...\n");
  49. sleep(3);
  50. fprintf(stderr, "Child exiting.\n");
  51. exit(-1);
  52. }
  53. if ((pid3 = fork()) == 0) {
  54. fprintf(stderr, "The child process sleeps 4 seconds...\n");
  55. sleep(2);
  56. fprintf(stderr, "Child exiting.\n");
  57. exit(-1);
  58. }
  59. fprintf(stderr, "Parent: waiting for the child to die.\n");
  60. status = 0;
  61. while (1) {
  62. wpid = waitpid(pid1, &result, WNOHANG);
  63. if (wpid == pid1)
  64. status |= GOT1;
  65. wpid = waitpid(pid2, &result, WNOHANG);
  66. if (wpid == pid2)
  67. status |= GOT2;
  68. wpid = waitpid(pid3, &result, WNOHANG);
  69. if (wpid == pid3)
  70. status |= GOT3;
  71. if (status == (GOT1 | GOT2 | GOT3))
  72. break;
  73. }
  74. fprintf(stderr, "Child process exited.\nGoodbye.\n");
  75. return EXIT_SUCCESS;
  76. }
  77. /*
  78. Local Variables:
  79. c-file-style: "linux"
  80. c-basic-offset: 4
  81. tab-width: 4
  82. End:
  83. */