内核对信号的处理
函数原型:int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);
函数功能:给信号设置新的注册函数act,同时保留原有的信号处理函数在oldact
struct sigaction { void (*sa_handler)(int); void (*sa_sigaction)(int, siginfo_t *, void *); sigset_t sa_mask; int sa_flags; void (*sa_restorer)(void); };
int main(int argc, char *argv[]) { union sigval val; val.sival_int = 10; pid_t pid = atoi(argv[1]); if (sigqueue(pid, SIGHUP, val) == -1) { perror("sigqueue"); exit(EXIT_FAILURE); } printf("current pid:%d\n", getpid()); return 0; }
void signal_handler(int signum) { printf("signal_handler\n"); switch(signum) { case SIGHUP: printf("get signal: SIGHUP\n"); sleep(20); break; case SIGINT: printf("get signal: SIGINT\n"); break; case SIGQUIT: printf("get signal: SIGQUIT\n"); break; case SIGUSR1: printf("get signal: SIGQUIT\n"); break; default: printf("undefined signal\n"); } } void signal_sigaction(int signum, siginfo_t *parm, void *parm2) { printf("signal_sigaction"); switch(signum) { case SIGHUP: printf("get signal: SIGHUP\n"); sleep(20); break; case SIGINT: printf("get signal: SIGINT\n"); break; case SIGQUIT: printf("get signal: SIGQUIT\n"); break; case SIGUSR1: printf("get signal: SIGQUIT\n"); break; default: printf("undefined signal\n"); } printf("received data: %d\n", parm->si_value); printf("sending signal process pid: %d\n", parm->si_pid); } int main(int argc, char *argv[]) { struct sigaction act, old_act; act.sa_sigaction = signal_sigaction; act.sa_handler = signal_handler; sigemptyset(&act.sa_mask); sigaddset(&act.sa_mask, SIGUSR1); act.sa_flags = 0; //sa_flags must be set, or it will cause core dump //set 0 may cause signal losing //act.sa_flags = SA_RESETHAND | SA_NODEFER; //SA_RESETHAND: restore signal action to DEF //SA_SIGINFO: use sa_sigaction as signal handler //SA_NODEFER: umask sa_mask sigaction(SIGHUP, &act, &old_act); while(1); return 0; }