1.简介
Linux系统进行和信号处理的时候有2个函数可供选择,signals和sigaction
signals函数原型:void (*signal(int signum, void (*func))(int)))(int);
sigaction函数原型:int sigaction(int sig, const struct sigaction *act, struct sigaction *oact);
当处理下列31个系统信号使用signals函数也很方便,当然使用sigaction也可,sigaction可以看作是signals函数的升级版,可以做到更多细节问题。
sigaction完全可以替代signals函数并且可以传递一些自定义信号。下面信号定义列表摘自signal.h
/* Signals. */
SIGHUP | 1 | /* Hangup (POSIX). */ |
---|---|---|
SIGINT | 2 | /* Interrupt (ANSI). */ |
SIGQUIT | 3 | /* Quit (POSIX). */ |
SIGILL | 4 | /* Illegal instruction (ANSI). */ |
SIGTRAP | 5 | /* Trace trap (POSIX). */ |
SIGABRT | 6 | /* Abort (ANSI). */ |
SIGIOT | 6 | /* IOT trap (4.2 BSD). */ |
SIGBUS | 7 | /* BUS error (4.2 BSD). */ |
SIGFPE | 8 | /* Floating-point exception (ANSI). */ |
SIGKILL | 9 | /* Kill, unblockable (POSIX). */ |
SIGUSR1 | 10 | /* User-defined signal 1 (POSIX). */ |
SIGSEGV | 11 | /* Segmentation violation (ANSI). */ |
SIGUSR2 | 12 | /* User-defined signal 2 (POSIX). */ |
SIGPIPE | 13 | /* Broken pipe (POSIX). */ |
SIGALRM | 14 | /* Alarm clock (POSIX). */ |
SIGTERM | 15 | /* Termination (ANSI). */ |
SIGSTKFLT | 16 | /* Stack fault. */ |
SIGCLD | SIGCHLD | /* Same as SIGCHLD (System V). */ |
SIGCHLD | 17 | /* Child status has changed (POSIX). */ |
SIGCONT | 18 | /* Continue (POSIX). */ |
SIGSTOP | 19 | /* Stop, unblockable (POSIX). */ |
SIGTSTP | 20 | /* Keyboard stop (POSIX). */ |
SIGTTIN | 21 | /* Background read from tty (POSIX). */ |
SIGTTOU | 22 | /* Background write to tty (POSIX). */ |
SIGURG | 23 | /* Urgent condition on socket (4.2 BSD). */ |
SIGXCPU | 24 | /* CPU limit exceeded (4.2 BSD). */ |
SIGXFSZ | 25 | /* File size limit exceeded (4.2 BSD). */ |
SIGVTALRM | 26 | /* Virtual alarm clock (4.2 BSD). */ |
SIGPROF | 27 | /* Profiling alarm clock (4.2 BSD). */ |
SIGWINCH | 28 | /* Window size change (4.3 BSD, Sun). */ |
SIGPOLL | SIGIO | /* Pollable event occurred (System V). */ |
SIGIO | 29 | /* I/O now possible (4.2 BSD). */ |
SIGPWR | 30 | /* Power failure restart (System V). */ |
SIGSYS | 31 | /* Bad system call. */ |
SIGUNUSED | 31 |
2.信号使用
signals函数
#include <QCoreApplication>
#include <signal.h>
#include <QDebug>
void Signals_Handle(int signal)
{
qDebug()<<"recive signals:"<<signal;
}
int main(int argc, char *argv[])
{
/*注册信号*/
signal(SIGINT,Signals_Handle);
return 0;
}
当按下键盘ctrl+c以后捕捉到SIGINT信号
sigaction函数使用
void Signals_Handle(int signal)
{
qDebug()<<"recive signals:"<<signal;
}
int main(int argc, char *argv[])
{
int mySig = 10;
struct sigaction siga;
siga.sa_handler = Signals_Handle;
siga.sa_flags = 0;
memset(&siga.sa_mask, 0, sizeof(sigset_t));
sigaction(SIGSEGV, &siga, NULL); /*注册非法错误的信号*/
sigaction(mySig, &siga, NULL); /*注册自定义信号*/
raise(mySig); /*发送自定义信号*/
return 0;
}
按下ctrl+c可以看到结果
本人理解水平有限,更多细节可以查看man手册。如有不当请帮忙指出,也欢迎大家一起交流技术。
作者:费码程序猿
欢迎技术交流:QQ:255895056
转载请注明出处,如有不当欢迎指正