/** * More info? * a.dotreppe@aspyct.org * http://aspyct.org * @aspyct (twitter) * * Hope it helps :) */ #include #include #include // sigaction(), sigsuspend(), sig*() #include // alarm() void handle_signal(int signal); void handle_sigalrm(int signal); void wait_for_signal(int seconds); /* Usage example * * First, compile and run this program: * $ gcc signal.c * $ ./a.out * * It will print out its pid. Use it from another terminal to send signals * $ kill -HUP * $ kill -USR1 * $ kill -ALRM * $ ^C # SIGINT * * Exit the process with SIGKILL, SIGTERM */ int main() { struct sigaction sa; // Print pid, so that we can send signals from other shells pid_t pid = getpid(); // Setup the sighub handler sa.sa_handler = &handle_signal; // Restart the system call, if at all possible sa.sa_flags = SA_RESTART; // Block every signal during the handler sigfillset(&sa.sa_mask); // Intercept SIGHUP, SIGINT, and SIGUSR1 if (sigaction(SIGHUP, &sa, NULL) == -1) { perror("Error: cannot handle SIGHUP"); // Should not happen } if (sigaction(SIGINT, &sa, NULL) == -1) { perror("Error: cannot handle SIGINT"); // Should not happen } if (sigaction(SIGUSR1, &sa, NULL) == -1) { perror("Error: cannot handle SIGUSR1"); // Should not happen } // Will always fail, SIGKILL is intended to force kill your process if (sigaction(SIGKILL, &sa, NULL) == -1) { perror("Cannot handle SIGKILL"); // Will always happen printf("You can never handle SIGKILL anyway...\n"); } for (;;) { printf("\nMy pid is: %d\n", pid); printf("Suspending for ~15 seconds\n"); wait_for_signal(15); // Later to be replaced with a SIGALRM } } void handle_signal(int signal) { const char *signal_name; sigset_t pending; printf("handle_signal\n"); // Find out which signal we're handling switch (signal) { case SIGHUP: signal_name = "SIGHUP"; break; case SIGUSR1: signal_name = "SIGUSR1"; break; case SIGINT: signal_name = "SIGINT (but I don't feel like exiting now)"; break; default: fprintf(stderr, "Caught wrong signal: %d\n", signal); return; } /* * Please note that printf et al. are NOT safe to use in signal handlers. * Look for async safe functions. */ printf("Caught %s\n", signal_name); } void handle_sigalrm(int signal) { if (signal != SIGALRM) { fprintf(stderr, "Caught wrong signal: %d\n", signal); } printf("Got SIGALRM\n"); } void wait_for_signal(int seconds) { struct sigaction sa; sigset_t mask; sa.sa_handler = &handle_sigalrm; // Intercept and ignore SIGALRM sa.sa_flags = SA_RESETHAND; // Remove the handler after first signal sigfillset(&sa.sa_mask); sigaction(SIGALRM, &sa, NULL); // Get the current signal mask sigprocmask(0, NULL, &mask); // Unblock SIGALRM sigdelset(&mask, SIGALRM); // Wait with this mask alarm(seconds); sigsuspend(&mask); printf("sigsuspend() returned\n"); }