这种方法不不能用于 SIGKILL, SIGSTOP, 因为这两个信号不能捕捉,不能忽略。
#include <stdio.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
static struct sigaction siga;
static void multi_handler(int sig, siginfo_t *siginfo, void *context) {
// get pid of sender,
pid_t sender_pid = siginfo->si_pid;
if(sig == SIGINT) {
printf("INT, from [%d]\n", (int)sender_pid);
return;
} else if(sig == SIGQUIT) {
printf("Quit, bye, from [%d]\n", (int)sender_pid);
exit(0);
}
return;
}
int main(void)
{
siga.sa_sigaction = *multi_handler;
siga.sa_flags |= SA_SIGINFO; // get detail info
// change signal action,
if(sigaction(SIGINT, &siga, NULL) != 0) {
printf("error sigaction()");
return errno;
}
if(sigaction(SIGQUIT, &siga, NULL) != 0) {
printf("error sigaction()");
return errno;
}
while(1)
{
sleep(10);
}
}
测试:
$ ./signal &
[1] 12267
$ kill -2 12267
INT, from [4909]
$ ps aux | grep 4909
charles 4909 0.0 0.2 12340 10120 pts/19 Ss 09:20 0:02 -bash
4096就是 bash的PID
版权声明:本文为CaspianSea原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。