?? lab3.c
字號:
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#define BILLION 1000000000L
#include <sys/types.h>
#include <linux/limits.h>
struct alarm{
time_t hour;
time_t min;
time_t sec;
};
struct alarm beeper;
struct tm *tnow;
struct sigaction act1;
/* ARGSUSED */
static void interrupt(int signo, siginfo_t *info, void *context) {
time_t tcurrent2;
tcurrent2=time(NULL);
tnow=localtime(&tcurrent2);
if(tnow->tm_hour==beeper.hour&&tnow->tm_min==beeper.min)
{
if(tnow->tm_sec==beeper.sec||tnow->tm_sec==beeper.sec+1||tnow->tm_sec==beeper.sec+2||tnow->tm_sec==beeper.sec+3||tnow->tm_sec==beeper.sec+4||tnow->tm_sec==beeper.sec+5||tnow->tm_sec==beeper.sec+6||tnow->tm_sec==beeper.sec+7||tnow->tm_sec==beeper.sec+8||tnow->tm_sec==beeper.sec+9)
{
printf("\n%d:%d:%d \n",tnow->tm_hour,tnow->tm_min,tnow->tm_sec);
printf("\n");
printf("%d:%d:%d alarm on \n",beeper.hour,beeper.min,beeper.sec);
}
else{
printf("\n%d:%d:%d \n",tnow->tm_hour,tnow->tm_min,tnow->tm_sec);
printf("%d:%d:%d alarm time \n",beeper.hour,beeper.min,beeper.sec);
}
}
else{
printf("\n%d:%d:%d \n",tnow->tm_hour,tnow->tm_min,tnow->tm_sec);
printf("%d:%d:%d alarm time \n",beeper.hour,beeper.min,beeper.sec);
}
}
static int setinterrupt() {
struct sigaction act;
act.sa_flags = SA_SIGINFO;
act.sa_sigaction = interrupt;
if ((sigemptyset(&act.sa_mask) == -1) ||
(sigaction(SIGALRM, &act, NULL) == -1))
return -1;
return 0;
}
void catchctrlc(int signo) {
printf("\ntime :%d:%d:%d \n",tnow->tm_hour,tnow->tm_min,tnow->tm_sec);
printf("alarm :%d:%d:%d \n",beeper.hour,beeper.min,beeper.sec);
}
static int setcatchctrlc() {
//struct sigaction act1;
act1.sa_handler = catchctrlc;
act1.sa_flags = 0;
if ((sigemptyset(&act1.sa_mask) == -1) ||
(sigaction(SIGINT, &act1, NULL) == -1))
perror("Failed to set SIGINT to handle Ctrl-C");
}
static int setperiodic(double sec) {
timer_t timerid;
struct itimerspec value;
if (timer_create(CLOCK_REALTIME, NULL, &timerid) == -1)
return -1;
value.it_interval.tv_sec = (long)sec;
value.it_interval.tv_nsec = (sec - value.it_interval.tv_sec)*BILLION;
if (value.it_interval.tv_nsec >= BILLION) {
value.it_interval.tv_sec++;
value.it_interval.tv_nsec -= BILLION;
}
value.it_value = value.it_interval;
return timer_settime(timerid, 0, &value, NULL);
}
int main(void) {
time_t tcurrent;
tcurrent=time(NULL);
printf("date/time now: %s", ctime(&tcurrent));
printf("Enter alarm time: (hour, min, sec):");
scanf("%d%d%d",&beeper.hour,&beeper.min,&beeper.sec);
if (setinterrupt() == -1) {
perror("Failed to setup SIGALRM handler");
return 1;
}
if (setcatchctrlc(1.0) == -1) {
perror("Failed to setup ctrl-c interrupt");
return 1;
}
if (setperiodic(1.0) == -1) {
perror("Failed to setup periodic interrupt");
return 1;
}
for ( ; ; )
pause();
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -