/* NOTE: Like the code in lecture, this code omits error checks when * calling the various library and system calls. Your MP code should * check for errors. We omit it here so that the main steps of the * code are more clearly illustrated. */ #include #include /* Our signal handler: We will set it up so that this function * is called whenever the program receives a SIGINT (which is * caused by the user pressing control-c). */ void handle(int sig) { char handmsg[] = "Ha! Handled!!!\n"; int msglen = sizeof(handmsg); /* Note we have to use `write' here, not printf(), because * write is safe to use in a signal handler (printf might * cause problems if another signal handler is called * while we are executing this one. */ write(2, handmsg, msglen); } int main(int argc, char** argv) { /* We will use sigaction() to set up our signal handler. * It has us put some of its arguments inside a structure * `struct sigaction'. So here we are really just setting * up arguments to sigaction -- kind of annoying that we * have to give the arguments this way rather than just * passing them in directly, but that's life. */ struct sigaction sa; sa.sa_handler = handle; /* the most important argument: the handler function */ sa.sa_flags = 0; /* no special options */ sigemptyset(&sa.sa_mask); /* sa_mask is the set of signals to block while in * the signal handler `handle'. Here we block none, i.e., * the empty set of signals. */ /* Finally, we actually install the signal handler for * the signal SIGINT. The second argument is the options * we set above. The third is used for sigaction() to tell * us what the old signal handler used to be, but we don't * care about that so we pass in NULL (which in this case * is a valid thing to pass in -- see the sigaction man page). */ sigaction(SIGINT, &sa, NULL); /* Print some miscellaneous output... try pressing control-c * while this happens. */ while (1) { printf("Fish.\n"); sleep(1); } }