previous | start | next

Solution: Blocking/Unblocking Signals

    1   
    2   pid_t pid;
    3   int counter = 0;
    4   
    5   void handler1(int sig)
    6   {
    7     counter++;
    8     printf("counter = %d\n", counter);
    9     fflush(stdout);
   10     kill(pid, SIGUSR1);
   11   }
   12   
   13   void handler2(int sig)
   14   {
   15     counter += 3;
   16     printf("counter = %d\n", counter);
   17     exit(0);
   18   }
   19   
   20   int main()
   21   {
   22     sigset_t s;
   23   
   24     Signal(SIGUSR1, handler1);
   25   
   26     sigemptyset(&s);
   27     sigaddset(&s, SIGUSR1);
   28     sigprocmask(SIG_BLOCK, &s, 0);
   29   
   30     if ((pid = fork()) == 0) {
   31       sigprocmask(SIG_UNBLOCK, &s, 0);
   32       Signal(SIGUSR1, handler2);
   33       kill(getppid(), SIGUSR1);
   34       while(1) {
   35       }
   36     } else {
   37       pid_t p; 
   38       int status;
   39       sigprocmask(SIG_UNBLOCK, &s, 0);
   40       if ((p = wait(&status)) > 0) {
   41         counter += 2;
   42         printf("counter = %d\n", counter);
   43   
   44       }
   45     }
   46   
   47     return 0;
   48   }


previous | start | next