📄 alarm.c
字号:
/* file: timer.c
function: show POSIX interval timer and signal handling
compile: gcc -o timer timer.c -lrt
run: ./timer
*/
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include<stdlib.h>
#include <linux/limits.h>
#include <time.h>
#include <signal.h>
#include "abstime.h"
int counter, counter_tmp;/* counter value*/
timer_t timer_id;
struct itimerspec time_out,abstime; /* time_out settings*/
struct timespec start, stop; /* start and stop time for the counter*/
int hour,min,sec;
struct tm *tptime;
time_t timep;
timer_data data;
int alarmflag=0;
void timer_handler( int signo);
void time_drift ( void );
int main(){
sigset_t mask;
struct sigaction sig_act;
struct sigevent evp;
int status;
/*timer_data data;
data.type = -1; */
counter=10;
counter_tmp=counter;
/* create a relative timer*/
sig_act.sa_handler = timer_handler;
sig_act.sa_flags = 0;
sigemptyset(&sig_act.sa_mask);
sigaction(SIGUSR1, & sig_act, NULL);
sig_alr.sa_handler = myhandler;
sig_alr.sa_flags = 0;
sigemptyset(&sig_alr.sa_mask);
sigaction(SIGALRM, &sig_alr, NULL);
evp.sigev_signo = SIGUSR1;
evp.sigev_notify = SIGEV_SIGNAL;
status = timer_create(CLOCK_REALTIME, &evp, &timer_id);
if (status == -1){
fprintf(stderr, "Error in timer_create\n");
exit(1);
}
printf("Enter the alarm time in this way\n hour:minuit:second:");
scanf("%d:%d:%d",&hour,&min,&sec);
time_out.it_value.tv_sec=1;
time_out.it_value.tv_nsec=0;
/* record start time*/
clock_gettime( CLOCK_REALTIME, & start);
abstm.it_value.tv_sec=start.tv_sec+time_out.it_value.tv_sec;
abstm.it_value.tv_nsec=start.tv_nsec+time_out.it_value.tv_nsec;
data.tvalue.it_value.tv_nsec += start.tv_nsec;
data.tvalue.it_value.tv_sec += start.tv_sec;
if (data.tvalue.it_value.tv_nsec >= BILLION) {
data.tvalue.it_value.tv_nsec -= BILLION;
data.tvalue.it_value.tv_sec++;
}
data.flags = TIMER_ABSTIME;
/* set timers */
status = timer_settime(timer_id, TIMER_ABSTIME, &abstm, NULL);
if (status == -1)
{
fprintf(stderr, "fail to set timer\n");
exit(1);
}
for(;;) pause();
}
void timer_handler( int signo )
{
time(&timep);
p=localtime(&timep);
if((p->tm_hour==hour) && (p->tm_min==min) && (p->tm_sec==sec))
{
alarm(10);
alarmflag=1;
printf("alarm on\n");
}
if(alarmflag==1)
printf("%d:%d:%d alarm time\n",p->tm_hour, p->tm_min, p->tm_sec);
if(alarmflag==0)
printf("%d:%d:%d\n",p->tm_hour, p->tm_min, p->tm_sec);
abstm.it_value.tv_sec+=time_out.it_value.tv_sec;
abstm.it_value.tv_nsec+=time_out.it_value.tv_nsec;
timer_settime(timer_id, TIMER_ABSTIME, &abstm, NULL);
}
static void myhandler()
{
alarmflag=0;
printf("alarm off\n");
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -