A signal is a small message that notifies a process that an event of some type has occurred in the system. Consider the following program.
#include <iostream>
#include "csapp.h"
using namespace std;
pid_t pid;
int counter = 2;
void handler1(int sig)
{
--counter;
cout << counter;
exit(0);
}
int main()
{
signal(SIGUSR1, handler1);
cout << counter;
if ((pid=fork()) == 0) {
while(1) {};
}
kill(pid, SIGUSR1);
waitpid(-1, NULL, 0);
++counter;
cout << counter;
exit(0);
}
What is the output of the program?
This program prints the string "213". The parent starts by printing "2", the forks the child, which spins in an infinite loop. Then parent then sends a signal to the child, and waits for it to terminate. The child catches the signal (interrupting the infinite loop), decrements the counter (from an initial value of 2), prints "1", and then terminates. After the parent reaps the child, it increments the counter (from an initial value of 2), prints "3", and terminates.