sigusr.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* Using kill for Communication
  2. Copyright (C) 1991-2026 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <https://www.gnu.org/licenses/>.
  13. */
  14. /*@group*/
  15. #include <signal.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <sys/types.h>
  19. #include <unistd.h>
  20. /*@end group*/
  21. /* When a @code{SIGUSR1} signal arrives, set this variable. */
  22. volatile sig_atomic_t usr_interrupt = 0;
  23. void
  24. synch_signal (int sig)
  25. {
  26. usr_interrupt = 1;
  27. }
  28. /* The child process executes this function. */
  29. void
  30. child_function (void)
  31. {
  32. /* Perform initialization. */
  33. printf ("I'm here!!! My pid is %d.\n", (int) getpid ());
  34. /* Let parent know you're done. */
  35. kill (getppid (), SIGUSR1);
  36. /* Continue with execution. */
  37. puts ("Bye, now....");
  38. exit (0);
  39. }
  40. int
  41. main (void)
  42. {
  43. struct sigaction usr_action;
  44. sigset_t block_mask;
  45. pid_t child_id;
  46. /* Establish the signal handler. */
  47. sigfillset (&block_mask);
  48. usr_action.sa_handler = synch_signal;
  49. usr_action.sa_mask = block_mask;
  50. usr_action.sa_flags = 0;
  51. sigaction (SIGUSR1, &usr_action, NULL);
  52. /* Create the child process. */
  53. child_id = fork ();
  54. if (child_id == 0)
  55. child_function (); /* Does not return. */
  56. /*@group*/
  57. /* Busy wait for the child to send a signal. */
  58. while (!usr_interrupt)
  59. ;
  60. /*@end group*/
  61. /* Now continue execution. */
  62. puts ("That's all, folks!");
  63. return 0;
  64. }