当前位置: 首页 > 工具软件 > Crypto-Signal > 使用案例 >

signal notes

席弘图
2023-12-01

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

SA_NOCLDSTOP
If signumis SIGCHLD, do not receive notification when child processes stop (i.e., when childprocesses receive one of SIGSTOP, SIGTSTP, SIGTTINor SIGTTOU).
SA_ONESHOT or SA_RESETHAND
Restore the signal action to the default state once the signal handlerhas been called.
SA_ONSTACK
Call the signal handler on an alternate signal stack provided by sigaltstack(2).If an alternate stack is not available, the default stack will be used.
SA_RESTART
Provide behaviour compatible with BSD signal semantics by making certainsystem calls restartable across signals.
SA_NOMASK or SA_NODEFER
Do not prevent the signal from being received from within its own signalhandler.
SA_SIGINFO
The signal handler takes 3 arguments, not one. In this case, sa_sigactionshould be set instead of sa_handler.(The sa_sigaction field was added in Linux 2.1.86.)

4. 若是攔截 Ctrl+c 或kill, process 將無法被外部結束. 記得要自己叫exit(0)

 类似资料:

相关阅读

相关文章

相关问答