lib/timer.c: prevent pathological race condition
flock(1) uses the timer facility to interrupt a blocking flock(2) call. However, in a pathological case (or with a sufficiently short timeout), the timer may fire and the signal be delivered after the timer is set up, but before we get around to doing the flock(2) call. In that case, we'd block forever. Checking timeout_expired right before calling flock(2) does not eliminate that race, so the only option is to make the timer fire repeatedly. Having the timer fire after we've returned from flock(2) is not a problem, since we only check timeout_expired in case of EINTR (also, this firing after return could also happen with the current code). There is currently one other user of setup_timer (misc-utils/uuidd.c), but in that case the signal handler simply exits. Future users of setup_timer obviously need to ensure that they can tolerate multiple signal deliveries. Choosing 1% of the initial timeout as the repeating interval is somewhat arbitrary. However, I put a lower bound of 0.01s, since setting the interval much smaller than this may end up effectively live-locking the process, handling a never-ending stream of signals. Signed-off-by: Rasmus Villemoes <rasmus.villemoes@prevas.dk>
This commit is contained in:
parent
c6a9147fd8
commit
e2cd1072b4
10
lib/timer.c
10
lib/timer.c
|
@ -13,16 +13,18 @@
|
||||||
int setup_timer(timer_t * t_id, struct itimerval *timeout,
|
int setup_timer(timer_t * t_id, struct itimerval *timeout,
|
||||||
void (*timeout_handler)(int, siginfo_t *, void *))
|
void (*timeout_handler)(int, siginfo_t *, void *))
|
||||||
{
|
{
|
||||||
|
time_t sec = timeout->it_value.tv_sec;
|
||||||
|
long usec = timeout->it_value.tv_usec;
|
||||||
struct sigaction sig_a;
|
struct sigaction sig_a;
|
||||||
static struct sigevent sig_e = {
|
static struct sigevent sig_e = {
|
||||||
.sigev_notify = SIGEV_SIGNAL,
|
.sigev_notify = SIGEV_SIGNAL,
|
||||||
.sigev_signo = SIGALRM
|
.sigev_signo = SIGALRM
|
||||||
};
|
};
|
||||||
struct itimerspec val = {
|
struct itimerspec val = {
|
||||||
.it_value.tv_sec = timeout->it_value.tv_sec,
|
.it_value.tv_sec = sec,
|
||||||
.it_value.tv_nsec = timeout->it_value.tv_usec * 1000,
|
.it_value.tv_nsec = usec * 1000,
|
||||||
.it_interval.tv_sec = 0,
|
.it_interval.tv_sec = sec / 100,
|
||||||
.it_interval.tv_nsec = 0
|
.it_interval.tv_nsec = (sec ? sec % 100 : 1) * 10*1000*1000
|
||||||
};
|
};
|
||||||
|
|
||||||
if (sigemptyset(&sig_a.sa_mask))
|
if (sigemptyset(&sig_a.sa_mask))
|
||||||
|
|
Loading…
Reference in New Issue