20 Alarms, sigaction(), and Reentrant System Calls

1 Alarm Signals and SIGALRM

1.1 Setting an alarm

  1. unsigned int alarm(unsigned int seconds);
  2. 过n秒后向进程发送SIGALARM信号
  3. SIGALARM信号默认动作是terminate
#include <stdio.h>
#include <stdlib.h>

#include <unistd.h>
#include <signal.h>
#include <sys/signal.h>

void alarm_handler(int signum){
  printf("Buzz Buzz Buzz\n");
}

int main(){

  //set up alarm handler
  signal(SIGALRM, alarm_handler);

  //schedule alarm for 1 second
  alarm(1);

  //do not proceed until signal is handled
  pause();

}

1.2 Recurring Alarms

/* buzz_buzz.c*/
  void alarm_handler(int signum){
    printf("Buzz Buzz Buzz\n");

    //set a new alarm for 1 second
    alarm(1);
  }

  int main(){

    //set up alarm handler
    signal(SIGALRM, alarm_handler);

    //schedule the first alarm
    alarm(1);

    //pause in a loop
    while(1){
      pause();
    }

  }

1.3 Resetting Alarms

void sigint_handler(int signum){
  printf("Snoozing!\n");

  //schedule next alarm for 5 seconds
  alarm(5);
}

void alarm_handler(int signum){
  printf("Buzz Buzz Buzz\n");

  //set a new alarm for 1 second
  alarm(1);
}

int main(){

  //set up alarm handler
  signal(SIGALRM, alarm_handler);

  //set up signint handler
  signal(SIGINT, sigint_handler);

  //schedule the first alarm
  alarm(1);

  //pause in a loop
  while(1){
    pause();
  }

}

2 sigaction() and Reentrant Functions

2.1 sigaction()

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

struct sigaction {
  void     (*sa_handler)(int);
  void     (*sa_sigaction)(int, siginfo_t *, void *);
  sigset_t   sa_mask;
  int        sa_flags;
};
void handler(int signum){
  printf("Hello World!\n");
}

int main(){

  //declare a struct sigaction
  struct sigaction action;

  //set the handler
  action.sa_handler = handler;

  //call sigaction with the action structure
  sigaction(SIGALRM, &action, NULL);

  //schedule an alarm
  alarm(1);

  //pause
  pause();
}

2.2 Reentrant Functions

2.3 Interrupting System call EINTR

2.4 SA_RESTART

2.5 Not all System Calls are Reentrant

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值