Guest User

sighup_EINTR_example

a guest
Jan 23rd, 2018
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.47 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <signal.h>
  3. #include <pthread.h>
  4. #include <stdatomic.h>
  5. #include <unistd.h>
  6. #include <sys/wait.h>
  7. #include <stdlib.h>
  8.  
  9. /*
  10.  * Set this variable if any signal is received
  11.  */
  12. volatile sig_atomic_t sig_set_flag = 0;
  13.  
  14. pthread_mutex_t cleanup_mutex;
  15.  
  16. /*
  17.  * Resource cleanup function.
  18.  */
  19. int cleaup_resources() {
  20.  
  21.     pthread_mutex_lock(&cleanup_mutex);
  22.     /*  
  23.      * Send notification to all the clients.
  24.      * Delete all the temp files
  25.      */
  26.     printf("Notified to clients.Exiting process\n");
  27.     pthread_mutex_unlock(&cleanup_mutex);
  28.  
  29.     return 0;
  30. }
  31.  
  32. /*
  33.  * Signal handler thread
  34.  */
  35. void sig_term_handler(int sig_num) {
  36.   sig_set_flag = sig_num;    
  37. }
  38.  
  39.  
  40. int main()
  41. {
  42.     int loop_count,status;
  43.     pthread_t tid;
  44.     pid_t pid;
  45.     int ret;
  46.     struct sigaction sig;
  47.     sig.sa_handler = &sig_term_handler;
  48.     sig.sa_flags = 0;
  49.     sigaction(SIGHUP, &sig, NULL);
  50.  
  51.     /*
  52.      * Spawn a thread to monitor signals.
  53.      * If signal received, Exit the process.
  54.      */
  55.     while(1) {
  56.      printf("Some time consuming task in progress... PID = %d\n",getpid());
  57.      pid = fork();
  58.      if(pid == 0) {
  59.  
  60.          sleep(100);
  61.          return 0;
  62.      } else {
  63.      ret = waitpid(pid, &status, 0);
  64.      if( (ret == -1) && (errno == EINTR) ) {
  65.          printf("System call interrpted\n");
  66.      }
  67.      loop_count++;
  68.      if( loop_count>=10)
  69.         break;
  70.      }
  71.     }
  72.     cleaup_resources();
  73.     exit(0);
  74.  
  75. }
Add Comment
Please, Sign In to add comment