#include <signal.h> typedef void (*sighandler_t)(int); sighandler_t signal (int signo, sighandler_t handler);
signal() removes the current action taken on receipt of the signal signo and instead handles the signal with the signal handler specified by handler
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <signal.h> /* handler for SIGINT and SIGTERM */ static void signal_handler (int signo) { if (signo == SIGINT) printf ("Caught SIGINT!\n"); else if (signo == SIGTERM) printf ("Caught SIGTERM!\n"); else { /* this should never happen */ fprintf (stderr, "Unexpected signal!\n"); exit (EXIT_FAILURE); } exit (EXIT_SUCCESS); } int main (void) { /* * Register signal_handler as our signal handler * for SIGINT. */ if (signal (SIGINT, signal_handler) == SIG_ERR) { fprintf (stderr, "Cannot handle SIGINT!\n"); exit (EXIT_FAILURE); } /* * Register signal_handler as our signal handler * for SIGTERM. */ if (signal (SIGTERM, signal_handler) == SIG_ERR) { fprintf (stderr, "Cannot handle SIGTERM!\n"); exit (EXIT_FAILURE); } /* Reset SIGPROF's behavior to the default. */ if (signal (SIGPROF, SIG_DFL) == SIG_ERR) { fprintf (stderr, "Cannot reset SIGPROF!\n"); exit (EXIT_FAILURE); } /* Ignore SIGHUP. */ if (signal (SIGHUP, SIG_IGN) == SIG_ERR) { fprintf (stderr, "Cannot ignore SIGHUP!\n"); exit (EXIT_FAILURE); } for (;;) pause (); return 0; }
#include <signal.h> int sigaction (int signo, const struct sigaction *act, struct sigaction *oldact); struct sigaction { void (*sa_handler)(int); /* signal handler or action */ void (*sa_sigaction)(int, siginfo_t *, void *); sigset_t sa_mask; /* signals to block */ int sa_flags; /* flags */ void (*sa_restorer)(void); /* obsolete and non-POSIX */ };
int ret; ret = kill (1722, SIGHUP); if (ret) perror ("kill");
$ kill -HUP 1722
/* a simple way for a process to send a signal to itself */ #include <signal.h> int raise (int signo);
raise (signo);
等同于:
kill (getpid (), signo);