#include <stdio.h> #include <unistd.h> #include <signal.h> void signal_handler(int signum) { printf("signal number %d received\n", signum); } int main(void) { struct sigaction action = {.sa_handler = signal_handler}; sigaction(SIGUSR1, &action, NULL); printf("I am process %d waiting for signal %d\n", getpid(), SIGUSR1); // loop waiting for signal // bad consumes CPU/electricity/battery // sleep would be better while (1) { } }
#include <stdio.h> #include <unistd.h> #include <signal.h> void signal_handler(int signum) { printf("signal number %d received\n", signum); } int main(void) { struct sigaction action = {.sa_handler = signal_handler}; sigaction(SIGUSR1, &action, NULL); printf("I am process %d waiting for signal %d\n", getpid(), SIGUSR1); // suspend execution for 1 hour sleep(3600); }
#include <stdio.h> #include <signal.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s <signal> <pid>\n", argv[0]); return 1; } int signal = atoi(argv[1]); int pid = atoi(argv[2]); kill(pid, signal); }
#include <stdio.h> #include <unistd.h> #include <signal.h> int main(void) { // catch SIGINT which is sent if user types cntrl-d struct sigaction action = {.sa_handler = SIG_IGN}; sigaction(SIGINT, &action, NULL); while (1) { printf("Can't interrupt me, I'm ignoring ctrl-C\n"); sleep(1); } }
#include <stdio.h> #include <unistd.h> #include <signal.h> void ha_ha(int signum) { printf("Ha Ha!\n"); // I/O can be unsafe in a signal handler } int main(void) { // catch SIGINT which is sent if user types cntrl-d struct sigaction action = {.sa_handler = ha_ha}; sigaction(SIGINT, &action, NULL); while (1) { printf("Can't interrupt me, I'm ignoring ctrl-C\n"); sleep(1); } }
#include <stdio.h> #include <unistd.h> #include <signal.h> int signal_received = 0; void stop(int signum) { signal_received = 1; } int main(void) { // catch SIGINT which is sent if user types cntrl-C struct sigaction action = {.sa_handler = stop}; sigaction(SIGINT, &action, NULL); while (!signal_received) { printf("Type ctrl-c to stop me\n"); sleep(1); } printf("Good bye\n"); }
#include <stdio.h> #include <unistd.h> #include <signal.h> #include <stdlib.h> void report_signal(int signum) { printf("Signal %d received\n", signum); printf("Please send help\n"); exit(0); } int main(int argc, char *argv[]) { struct sigaction action = {.sa_handler = report_signal}; sigaction(SIGFPE, &action, NULL); // this will produce a divide by zero // if there are no command-line arguments // which will cause program to receive SIGFPE printf("%d\n", 42/(argc - 1)); printf("Good bye\n"); }