20 Alarms, sigaction(), and Reentrant System Calls

荒凉一梦 提交于 2019-12-23 00:27:41

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!