Here's a short puzzle to ensure you understand key ideas:
- We'll first work through a small puzzle to confirm you all understand the workflow of the processes and understand how kill triggers various signal handlers to be executed. (Error checking is omitted from this example, since it's so small, and we'll assume, for simplicity, that nothing ever fails).
- Putting it all together. What're the possible outputs (plural!) of the following program?
static pid_t pid;
static int counter = 0;
static void parentHandler(int unused) { static void childHandler(int unused) {
counter++; counter += 3;
printf("counter = %d\n", counter); printf("counter = %d\n", counter);
kill(pid, SIGUSR1); }
}
int main(int argc, char *argv[]) {
signal(SIGUSR1, parentHandler);
if ((pid = fork()) == 0) {
signal(SIGUSR1, childHandler);
kill(getppid(), SIGUSR1);
return 0;
}
waitpid(pid, NULL, 0);
counter += 7;
printf("counter = %d\n", counter);
return 0;
}