1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static volatile sig_atomic_t ball_count = 0;

void sighandler(int sig) {
   ++ball_count;
   if (signal(sig, sighandler) == SIG_ERR) _Exit(1);
}

static void playwith(pid_t partner) {
   for(int i = 0; i < 10; ++i) {
      if (!ball_count) pause();
      printf("[%d] send signal to %d\n",
         (int) getpid(), (int) partner);
      if (kill(partner, SIGUSR1) < 0) {
         printf("[%d] %d is no longer alive\n",
            (int) getpid(), (int) partner);
         break;
      }
      --ball_count;
   }
   printf("[%d] finishes playing\n", (int) getpid());
}

int main() {
   /* this signal setting is inherited to our child */
   if (signal(SIGUSR1, sighandler) == SIG_ERR) {
      perror("signal SIGUSR1"); exit(1);
   }

   pid_t parent = getpid(); 
   pid_t child = fork();
   if (child < 0) {
      perror("fork"); exit(1);
   }
   if (child == 0) {
      ball_count = 1; /* give the ball to the child... */
      playwith(parent);
   } else {
      playwith(child);
   }
}