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 : 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值