wake-up signal SIGALRM from alarm() or setitimer(). SIG_DFL & SIG_IGN

简介:
SIGALRM信号, 一般可以由alarm或者setitmer来发出。 可以用于定多长时间触发一个事件.
例如在等待用户输入时, 超过多少秒就触发这个信号. 在触发后, 用户输入被中断, 跳转到信号处理函数, 信号处理函数结束后, 接着用户输入的下一个语句执行, 用户输入不再执行. 如下 :
[root@db-172-16-3-150 zzz]# cat a.c
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#define TIMEOUT 5

void error(char * msg) {
  fprintf(stdout, "%s: %s\n", msg, strerror(errno));
  exit(1);
}

void alrm_handler(int sig) {
  fprintf(stdout, "sig:%i, Sorry, TIME IS UP. Please enter your name within %i second.\n", sig, TIMEOUT);
  alarm(TIMEOUT);
  //exit(1);
}

int reg_handler(int sig, void (*handler)(int)) {
  struct sigaction action;
  action.sa_handler = handler;
  sigemptyset(&action.sa_mask);
  action.sa_flags = 0;
  return sigaction(sig, &action, NULL);
}

int main() {
  char fname[80];
  char lname[80];
  alarm(TIMEOUT);
  if( reg_handler(SIGALRM, alrm_handler) == -1 ) {
    error("reg_handler error");
  }
  fprintf(stdout, "please enter your first name: ");
  fgets(fname, 80, stdin);
  // 第一次超时后, 从下面开始执行.
  fprintf(stdout, "please enter your last name: ");
  fgets(lname, 80, stdin);
  // 第二次超时后, 从下面开始执行.
  fprintf(stdout, "Hello, %s.%s\n", lname, fname);
  return 0;
}

执行 : 
[root@db-172-16-3-150 zzz]# gcc -O3 -Wall -Wextra -Werror -g ./a.c -o a
[root@db-172-16-3-150 zzz]# ./a
please enter your first name: sig:14, Sorry, TIME IS UP. Please enter your name within 5 second. 
please enter your last name: sig:14, Sorry, TIME IS UP. Please enter your name within 5 second.
Hello, ?

注意这个程序有问题, 因为每隔5秒就会触发这个信号.
应该改成 : 

[root@db-172-16-3-150 zzz]# cat a.c
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#define TIMEOUT 5

void error(char * msg) {
  fprintf(stdout, "%s: %s\n", msg, strerror(errno));
  exit(1);
}

void alrm_handler(int sig) {
  fprintf(stdout, "sig:%i, Sorry, TIME IS UP. Please enter your name within %i second.\n", sig, TIMEOUT);
  // 一般在信号处理函数中使用exit, 这么做的话程序就直接退出了. 当然你可以选择不用. 例如定时执行其他任务的, 就不需要exit. 
  exit(1);
}

int reg_handler(int sig, void (*handler)(int)) {
  struct sigaction action;
  action.sa_handler = handler;
  sigemptyset(&action.sa_mask);
  action.sa_flags = 0;
  return sigaction(sig, &action, NULL);
}

int main() {
  char fname[80];
  char lname[80];
  if( reg_handler(SIGALRM, alrm_handler) == -1 ) {
    error("reg_handler error");
  }
  alarm(TIMEOUT);
  fprintf(stdout, "please enter your first name: ");
  fscanf(stdin, "%80s", fname);
  // 时间在这里剩余2秒时, 重新调用alarm(TIMEOUT) 又会把计时器调整为5秒,  覆盖前面的剩余时间. 
  alarm(TIMEOUT);
  fprintf(stdout, "please enter your last name: ");
  fscanf(stdin, "%80s", lname);
  fprintf(stdout, "Hello, %s.%s\n", lname, fname);
  return 0;
}


在程序中要忽略某些信号或者要还原信号处理函数怎么办呢?
sa_handler specifies the action to be associated with signum and may be SIG_DFL for the default action, SIG_IGN
       to ignore this signal, or a pointer to a signal handling function.  This function receives the signal number as
       its only argument.


如果在程序中要忽略对信号的响应. 使用如下方法 : 
reg_handler(SIGALRM, SIG_IGN), 表示遇到SIGALRM信号不作任何响应.
例如在以上代码中添加

  if( reg_handler(SIGINT, SIG_IGN) == -1 ) {
    error("reg_handler error");
  }

则在程序执行过程中使用 "kill -INT 进程号", 或者"键入CTRL+C" 都无响应.

如果在程序中要还原原来的signal handler, 使用如下 : 
reg_handler(SIGINT, SIG_DFL);

注意, 

NAME
       sigaction - examine and change a signal action
SYNOPSIS
       #include <signal.h>
       int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);
DESCRIPTION
       The sigaction() system call is used to change the action taken by a process on receipt of a specific signal.
       signum specifies the signal and can be any valid signal except SIGKILL and SIGSTOP.

因为SIGKILL和SIGSTOP信号不能调用sigaction注册handler function. 所以也就不存在忽略这两个信号的可能了.

下面的例子, 问问题, 如果5秒内未答出则超时, 并raise(SIGINT) , 调用end_game结束程序. 或者直接ctrl+c 发出SIGINT信号调用end_game结束程序 : 

[root@db-172-16-3-150 zzz]# cat a.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include <signal.h>

#define TIMEOUT 5

int score = 0;

void end_game(int sig) {
  printf("\nsig:%i, Final score: %i\n", sig, score);
  exit(0);
}

int catch_signal (int sig, void (*handler)(int)) {
  struct sigaction action;
  action.sa_handler = handler;
  sigemptyset(&action.sa_mask);
  action.sa_flags = 0;
  return sigaction (sig, &action, NULL);
}

void times_up(int sig) {
  fprintf(stdout, "\nsig:%i, TIME'S UP!", sig);
  raise(SIGINT);
}

void error(char *msg) {
  fprintf(stderr, "%s: %s\n", msg, strerror(errno));
  exit(1);
}
int main() {
  catch_signal(SIGALRM, times_up);
  catch_signal(SIGINT, end_game);
  srandom (time (0));
  while(1) {
    int a = random() % 11;
    int b = random() % 11;
    char txt[4];
    alarm(TIMEOUT);
    printf("\nWhat is %i times %i? ", a, b);
    fgets(txt, 4, stdin);
    int answer = atoi(txt);
    if (answer == a * b)
      score++;
    else
      printf("\nWrong! Score: %i\n", score);
  }
  return 0;
}


其他 :
Q: Are signals always received in the same order they are sent?
A: Not if they are sent very close together. 
The operating system might choose to reorder the signals if it thinks one is more important than the others.
Q: Is that always true?
A: It depends on the platform. 
On most versions of Cygwin, for example, the signals will always be sent and received in the same order. 
But in general, you shouldn’t rely on it.
Q: If I send the same signal twice, will it be received twice by the process?
A: Again, it depends. 
On Linux and the Mac, if the same signal is repeated very quickly, the kernel might choose to only send the signal once to the process. 
On Cygwin, it will always send both signals. 
But again, you should not assume that just because you sent the same signal twice, it will be received twice


【参考】
setitimer : 

目录
相关文章
|
JavaScript Java 测试技术
基于springboot+vue.js+uniapp小程序的房价数据分析附带文章源码部署视频讲解等
基于springboot+vue.js+uniapp小程序的房价数据分析附带文章源码部署视频讲解等
78 0
|
存储 机器学习/深度学习 负载均衡
使用梯度提升树算法进行CTR预测
使用梯度提升树算法进行CTR预测
486 0
|
数据采集 存储 应用服务中间件
使用go做一个限流功能
使用go做一个限流功能
189 0
|
算法 C语言
C语言基础(有关三角形面积,阶乘算法,sqrt,pow函数,海伦公式,gets,getchar,scanf的区别,字符转换,增长率计算,的分支和循环的结构程序设计)
C语言基础(有关三角形面积,阶乘算法,sqrt,pow函数,海伦公式,gets,getchar,scanf的区别,字符转换,增长率计算,的分支和循环的结构程序设计)
|
机器学习/深度学习 算法 数据可视化
黑马程序员---三天快速入门Python机器学习(第二天)(下)
黑马程序员---三天快速入门Python机器学习(第二天)
114 0
黑马程序员---三天快速入门Python机器学习(第二天)(下)
python基于淘宝历史数据的用户行为分析(四)
python基于淘宝历史数据的用户行为分析(四)
python基于淘宝历史数据的用户行为分析(四)