sigaction信号处理

来源:互联网 发布:java监听器原理 编辑:程序博客网 时间:2024/04/30 02:35

1. sigaction

int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);

signum:可以指定SIGKILL和SIGSTOP以外的所有信号

2. struct sigaction

struct sigaction {    void     (*sa_handler)(int);    void     (*sa_sigaction)(int, siginfo_t *, void *);    sigset_t   sa_mask;    int        sa_flags;    void     (*sa_restorer)(void);};

sa_mask:设置在处理该信号时暂时将sa_mask 指定的信号集搁置
sa_flags:设置信号处理相关操作

  • SA_SIGINFO:如果设置,那么采用sa_sigaction;默认采用sa_handler
  • SA_RESETHAND:当调用信号处理函数时,将信号的处理函数重置为缺省值SIG_DFL
  • SA_RESTART:如果信号中断了进程的某个系统调用,则系统自动启动该系统调用
  • SA_NODEFER :一般情况下, 当信号处理函数运行时,内核将阻塞该给定信号。但是如果设置了 SA_NODEFER标记, 那么在该信号处理函数运行时,内核将不会阻塞该信号

sa_restorer:此参数没有使用

3. siginfo_t

siginfo_t{    int      si_signo;  /* 信号值,对所有信号有意义*/    int      si_errno;  /* errno值,对所有信号有意义*/    int      si_code;   /* 信号产生的原因,对所有信号有意义*/    int      si_trapno; /* Trap number that caused                           hardware-generated signal                           (unused on most architectures) */    pid_t    si_pid;    /* 发送信号的进程ID,对kill(2),实时信号以及SIGCHLD有意义 */    uid_t    si_uid;    /* 发送信号进程的真实用户ID,对kill(2),实时信号以及SIGCHLD有意义 */    int      si_status; /* 退出状态,对SIGCHLD有意义*/    clock_t  si_utime;  /* 用户消耗的时间,对SIGCHLD有意义 */    clock_t  si_stime;  /* 内核消耗的时间,对SIGCHLD有意义 */    sigval_t si_value;  /* 信号值,对所有实时有意义,是一个联合数据结构,                           可以为一个整数(由si_int标示,也可以为一个指针,由si_ptr标示)*/    int      si_int;    /* POSIX.1b signal */    void    *si_ptr;    /* POSIX.1b signal */    int      si_overrun;/* Timer overrun count; POSIX.1b timers */    int      si_timerid;/* Timer ID; POSIX.1b timers */    void *   si_addr;   /* 触发fault的内存地址,对SIGILL,SIGFPE,SIGSEGV,SIGBUS 信号有意义*/    int      si_band;   /* 对SIGPOLL信号有意义 */    int      si_fd;     /* 对SIGPOLL信号有意义 */}

4. si_value
通过siginfo_t.si_value可以获得sigqueue(pid_t pid, int sig, const union sigval val)第三个参数传递过来的数据
如:siginfo_t.si_value.sival_int或siginfo_t.si_value.sival_ptr
其实siginfo_t.si_int直接与sigval.sival_int关联,siginfo_t.si_ptr直接与sigval.sival_ptr关联。所以也可同这种方式获得sigqueue发送过来的数据

si_value

5. sigqueue

int sigqueue(pid_t pid, int sig, const union sigval value);
union sigval {    int   sival_int;    void *sival_ptr;};

6. 举例

struct sigaction act, oact;act.sa_handler = int_hander;sigemptyset(&act.sa_mask); //清空此信号集act.sa_flags = 0;sigaction(SIGINT, &act, &oact);sigaction(SIGINT, &oact, NULL); //恢复成原始状态
struct sigaction act;act.sa_sigaction = sig_handler;sigemptyset(&act.sa_mask); //清空此信号集act.sa_flags = SA_SIGINFO;sigaction(SIGCHLD, &act, &p_ctx->oact);union sigval var;//var.sival_int = 3var.sival_ptr = (void *)&val;sigqueue(pid, SIGCHLD, var);

SIGCHLD信号被设置,sigaction主动发送一次信号;子进程退出,系统还会调用sig_handler信号处理,此时携带参数为0

参考文献:
http://blog.csdn.net/wangpengqi/article/details/11632567

0 0
原创粉丝点击