#include #include #include #include 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); } }