1. code example
#include <signal.h>
static void my_signal_handler(int sig)
{
printf("receive signal %d", sig);
}
int main(/*int argc, char **argv*/) {
struct sigaction sa;
/* Set up the signal handler */
sa.sa_handler = my_signal_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_ONESHOT;
/* 攔截Ctl+C 及 kill */
if (sigaction(SIGINT , &sa, NULL) == -1) {
return 1;
}
if (sigaction(SIGTERM , &sa, NULL) == -1) {
return 1;
}
}
2 常見 signal id
#define SIGINT 2 /* Interrupt (ANSI). */ 按 Ctl + C |
#define SIGQUIT 3 /* Quit (POSIX). */ |
#define SIGILL 4 /* Illegal instruction (ANSI). */ |
#define SIGTRAP 5 /* Trace trap (POSIX). */ |
#define SIGABRT 6 /* Abort (ANSI). */ |
#define SIGIOT 6 /* IOT trap (4.2 BSD). */ |
#define SIGBUS 7 /* BUS error (4.2 BSD). */ |
#define SIGFPE 8 /* Floating-point exception (ANSI). */ |
#define SIGKILL 9 /* Kill, unblockable (POSIX). */ 不可用 |
#define SIGUSR1 10 /* User-defined signal 1 (POSIX). */ |
#define SIGSEGV 11 /* Segmentation violation (ANSI). */ |
#define SIGUSR2 12 /* User-defined signal 2 (POSIX). */ |
#define SIGPIPE 13 /* Broken pipe (POSIX). */ |
#define SIGALRM 14 /* Alarm clock (POSIX). */ |
#define SIGTERM 15 /* Termination (ANSI). */ kill <process id> |
#define SIGSTKFLT 16 /* Stack fault. */ |
#define SIGCLD SIGCHLD /* Same as SIGCHLD (System V). */ |
#define SIGCHLD 17 /* Child status has changed (POSIX). */ |
#define SIGCONT 18 /* Continue (POSIX). */ |
#define SIGSTOP 19 /* Stop, unblockable (POSIX). */ 不可用 |
3. sa.sa_flags
4. 若是攔截 Ctrl+c 或kill, process 將無法被外部結束. 記得要自己叫exit(0)