Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. /* Make the process sleep for SECONDS seconds, or until a signal arrives
  2. and is not ignored. The function returns the number of seconds less
  3. than SECONDS which it actually slept (zero if it slept the full time).
  4. If a signal handler does a `longjmp' or modifies the handling of the
  5. SIGALRM signal while inside `sleep' call, the handling of the SIGALRM
  6. signal afterwards is undefined. There is no return value to indicate
  7. error, but if `sleep' returns SECONDS, it probably didn't work. */
  8.  
  9. /* sleep has a signal handler that stops on sigalrm
  10. * lets check it out:
  11. * Two threads, one to send events, one to sleep */
  12.  
  13. #include <unistd.h>
  14. #include <stdlib.h>
  15. #include <pthread.h>
  16. #include <signal.h>
  17. #include <stdio.h>
  18. #include <string.h>
  19.  
  20. char buffer[2000];
  21. void * sleeping();
  22. void handle_signal(int i);
  23.  
  24. int main(void)
  25. {
  26. /* setup thread */
  27. pthread_t sleeper;
  28. if(pthread_create(&sleeper, NULL, sleeping, NULL) != 0)
  29. {
  30. printf("Could not start sleeper thread\n");
  31. }
  32.  
  33. /* interrupt sleeping thread on user input */
  34. printf("Send a message to the sleeper\n");
  35. while(1)
  36. {
  37. fgets(buffer, 2000, stdin);
  38. raise(SIGALRM);
  39. }
  40.  
  41. /* join: this will never happen the way this is implemented */
  42. pthread_join(sleeper, NULL);
  43. exit(0);
  44. }
  45.  
  46. void * sleeping()
  47. {
  48. /* handle SIGALRM */
  49. struct sigaction action;
  50. sigset_t set;
  51. memset(&action, 0, sizeof(action));
  52. sigemptyset(&action.sa_mask);
  53. action.sa_flags = 0;
  54. action.sa_handler = handle_signal;
  55. sigaction(SIGALRM, &action, NULL);
  56.  
  57.  
  58. /* sleep until we get signal */
  59. while(1)
  60. {
  61. sleep(100000);
  62. printf("Woke Up!\n"); // when we run this never prints
  63. // which means after the sigalrm
  64. // we go back to sleep
  65. // while the default handling does not
  66. }
  67. }
  68.  
  69.  
  70. void handle_signal(int sig)
  71. {
  72. /* exit - make thread exit */
  73. if(strstr(buffer, "exit") != NULL)
  74. {
  75. exit(0);
  76. }
  77. else // echo message
  78. {
  79. write(1, "your message: ", 15);
  80. write(1, buffer, 2000);
  81. write(1, "\n", 2);
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement