Linux信号处理

信号是一种软件中断,程序收到信号时,就会调用相应的处理函数(如果有注册)。

void (*signal(int signum,void(* handler)(int)))(int); -- 设置信号处理方式
信号处理函数原型
void   foo(int arg);
 
系统定义的信号有:
/* Signals.  */
#define SIGHUP1/* Hangup (POSIX).  */
#define SIGINT2/* Interrupt (ANSI).  */
#define SIGQUIT3/* Quit (POSIX).  */
#define SIGILL4/* Illegal instruction (ANSI).  */
#define SIGTRAP5/* Trace trap (POSIX).  */
#define SIGABRT6/* Abort (ANSI).  */
#define SIGIOT6/* IOT trap (4.2 BSD).  */
#define SIGBUS7/* BUS error (4.2 BSD).  */
#define SIGFPE8/* Floating-point exception (ANSI).  */
#define SIGKILL9/* Kill, unblockable (POSIX).  */
#define SIGUSR110/* User-defined signal 1 (POSIX).  */
#define SIGSEGV11/* Segmentation violation (ANSI).  */
#define SIGUSR212/* User-defined signal 2 (POSIX).  */
#define SIGPIPE13/* Broken pipe (POSIX).  */
#define SIGALRM14/* Alarm clock (POSIX).  */
#define SIGTERM15/* Termination (ANSI).  */
#define SIGSTKFLT16/* Stack fault.  */
#define SIGCLDSIGCHLD/* Same as SIGCHLD (System V).  */
#define SIGCHLD17/* Child status has changed (POSIX).  */
#define SIGCONT18/* Continue (POSIX).  */
#define SIGSTOP19/* Stop, unblockable (POSIX).  */
#define SIGTSTP20/* Keyboard stop (POSIX).  */
#define SIGTTIN21/* Background read from tty (POSIX).  */
#define SIGTTOU22/* Background write to tty (POSIX).  */
#define SIGURG23/* Urgent condition on socket (4.2 BSD).  */
#define SIGXCPU24/* CPU limit exceeded (4.2 BSD).  */
#define SIGXFSZ25/* File size limit exceeded (4.2 BSD).  */
#define SIGVTALRM26/* Virtual alarm clock (4.2 BSD).  */
#define SIGPROF27/* Profiling alarm clock (4.2 BSD).  */
#define SIGWINCH28/* Window size change (4.3 BSD, Sun).  */
#define SIGPOLLSIGIO/* Pollable event occurred (System V).  */
#define SIGIO29/* I/O now possible (4.2 BSD).  */
#define SIGPWR30/* Power failure restart (System V).  */
#define SIGSYS31/* Bad system call.  */
#define SIGUNUSED31
 
#define_NSIG65/* Biggest signal number + 1
   (including real-time signals).  */
 
#define SIGRTMIN        (__libc_current_sigrtmin ())
#define SIGRTMAX        (__libc_current_sigrtmax ())
 
向进程发送信号(在终端)
kill -s signal pid  -- signal的值是上面列表中的合法值
kill -s 9 pid  -- 该命令会结束指定的进程
 
下面的例子显示进程接收到的信号
复制代码
#include <unistd.h>
#include <stdio.h>
#include <signal.h>

void handler(int arg)
{
    printf("get signal %d\n", arg);
    
}
int main()
{
    int i;
    for (i=0; i<SIGRTMAX; i++)
        signal(i, handler);
    while(1)
    {
        pause();
    }
    return 0;
}
复制代码
可以用kill -s 9 pid结束它
kill也是一个可调用的API
int kill(pid_t pid,int sig); 
kill()可以用来送参数 sig指定的信号给参数pid指定的进程。
参数pid有几种情况: 
pid>0 将信号传给进程识别码为 pid的进程。 
pid=0 将信号传给和目前进程相同进程组的所有进程 
pid=-1 将信号广播传送给系统内所有的进程
pid<0 将信号传给进程组识别码pid绝对值的所有进程
原文地址:https://www.cnblogs.com/spinsoft/p/2596866.html