Linux信号实例
SA_RESTART
-----------------------------------------
设置信号S的SA_RESTART属性, 如果系统调用被信号S中断, 当信号处理函数返回后,
将自动恢复该系统调用
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <string.h>
void sig_handler(int signum)
{
printf("at handler\n");
sleep(10);
printf("leave handler\n");
}
int main(int argc, char **argv)
{
char buf[100];
int ret;
struct sigaction action, old_action;
action.sa_handler = sig_handler;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
action.sa_flags |= SA_RESTART; /* 设置或者不设置此属性 */
sigaction(SIGINT, NULL, &old_action);
if (old_action.sa_handler != SIG_IGN) {
sigaction(SIGINT, &action, NULL);
}
bzero(buf, 100);
ret = read(0, buf, 100);
if (ret == -1) {
perror("read");
}
printf("read %d bytes:\n", ret);
printf("%s\n", buf);
return 0;
}
若不设置, 从标准输入读数据的时候,如果按下ctrl+c, 则read系统调用被中断, 返回-1
若设置, 信号处理函数返回后, 恢复read系统调用, 但信号处理返回之前, read是无法读取数据的
int sigemptyset(sigset_t *set);
int sigfillset(sigset_t *set);
int sigaddset(sigset_t *set, int signum);
int sigdelset(sigset_t *set, int signum);
int sigismember(const sigset_t *set, int signum);
int sigsuspend(const sigset_t *mask);
int sigpending(sigset_t *set);
屏蔽进程的某些信号
-------------------------------------
所谓屏蔽, 并不是禁止递送信号, 而是暂时阻塞信号的递送,
解除屏蔽后, 信号将被递送, 不会丢失
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <string.h>
void sig_handler(int signum)
{
printf("catch sigint\n");
}
int main(int argc, char **argv)
{
sigset_t block;
struct sigaction action, old_action;
action.sa_handler = sig_handler;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
sigaction(SIGINT, NULL, &old_action);
if (old_action.sa_handler != SIG_IGN) {
sigaction(SIGINT, &action, NULL);
}
sigemptyset(&block);
sigaddset(&block, SIGINT);
printf("block sigint\n");
sigprocmask(SIG_BLOCK, &block, NULL);
sleep(5);
/* unblock信号后, 之前触发的信号将被递送, 如果之前被
* 触发多次, 只会递送一次 */
sigprocmask(SIG_UNBLOCK, &block, NULL);
printf("unblock sigint\n");
sleep(5);
return 0;
}
在信号处理函数内, 屏蔽某些信号
----------------------------------------
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <stri
相关新闻>>
- 发表评论
-
- 最新评论 更多>>