-
Notifications
You must be signed in to change notification settings - Fork 50
/
timer.c
91 lines (76 loc) · 2.17 KB
/
timer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/* $Id$ */
/*
* Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <string.h>
#include "fdm.h"
volatile sig_atomic_t timer_value;
void timer_handler(int);
/* Signal handler for SIGALRM setitimer timeout. */
void
timer_handler(unused int sig)
{
timer_value = 1;
}
/* Return timer state. */
int
timer_expired(void)
{
return (timer_value);
}
/* Set timer with setitimer. */
void
timer_set(int seconds)
{
struct itimerval itv;
struct sigaction act;
if (seconds == 0)
fatalx("zero timeout");
timer_value = 0;
memset(&act, 0, sizeof act);
sigemptyset(&act.sa_mask);
act.sa_handler = timer_handler;
if (sigaction(SIGALRM, &act, NULL) != 0)
fatal("sigaction failed");
memset(&itv, 0, sizeof itv);
itv.it_value.tv_sec = seconds;
while (setitimer(ITIMER_REAL, &itv, NULL) != 0) {
/*
* If the timeout is too large (EINVAL), keep trying it until
* it reaches a minimum of 30 seconds.
*/
if (errno != EINVAL || itv.it_value.tv_sec < 30)
fatal("setitimer failed");
itv.it_value.tv_sec /= 2;
}
}
/* Unset timer. */
void
timer_cancel(void)
{
struct itimerval itv;
struct sigaction act;
memset(&itv, 0, sizeof itv);
if (setitimer(ITIMER_REAL, &itv, NULL) != 0)
fatal("setitimer failed");
memset(&act, 0, sizeof act);
sigemptyset(&act.sa_mask);
act.sa_handler = SIG_DFL;
if (sigaction(SIGALRM, &act, NULL) != 0)
fatal("sigaction failed");
}