Hi,
There's an edge case in lock(1) where, after you've reserved
a terminal for a finite time, if the system time is changed
you get an inaccurate report of the remaining time left on
the reservation.
This is because we subtract the result of time(3) at the
beginning of the program from the result of time(3) within the
signal handler to compute the time remaining.
If we use getitimer(2), we'll get the real time remaining on
the timer instead of a potentially inaccurate difference
relative to when the program started.
Of note (maybe?) is that neither gettimeofday(2) (called by
time(3)) nor getitimer(2) are async-safe interfaces as far as
signal(3) is concerned. I don't know whether this has any
meaningful implications, or whether they're even actually
unsafe at all.
While here, clean up a few things:
* Set the minimum field width for minutes in the time
remaining to 2 and add zero padding, to prevent printouts
like:
lock: type in the unlock key. timeout in 13:2 minutes
* Use dprintf(3) instead of snprintf(3) + write(2). Because
signal(3) says that snprintf(3) and dprintf(3) are both
async-safe, I think it's cleaner to just use dprintf(3)
directly.
CC'd tedu@ because he's on the commit trail for lock.c within
the last two years.
Thoughts?
--
Scott Cheloha
Index: usr.bin/lock/lock.c
===================================================================
RCS file: /cvs/src/usr.bin/lock/lock.c,v
retrieving revision 1.34
diff -u -p -r1.34 lock.c
--- usr.bin/lock/lock.c 3 May 2017 09:51:39 -0000 1.34
+++ usr.bin/lock/lock.c 2 Jul 2017 19:08:54 -0000
@@ -233,19 +233,16 @@ main(int argc, char *argv[])
void
hi(int signo)
{
- char buf[1024], buf2[1024];
- time_t left;
+ struct itimerval left;
- if (no_timeout)
- buf2[0] = '\0';
- else {
- left = nexttime - time(NULL);
- (void)snprintf(buf2, sizeof buf2, " timeout in %lld:%d minutes",
- (long long)(left / 60), (int)(left % 60));
+ (void)dprintf(STDERR_FILENO, "%s: type in the unlock key.", __progname);
+ if (!no_timeout) {
+ (void)getitimer(ITIMER_REAL, &left);
+ (void)dprintf(STDERR_FILENO, " timeout in %lld:%02d minutes",
+ (long long)(left.it_value.tv_sec / 60),
+ (int)(left.it_value.tv_sec % 60));
}
- (void)snprintf(buf, sizeof buf, "%s: type in the unlock key.%s\n",
- __progname, buf2);
- (void) write(STDERR_FILENO, buf, strlen(buf));
+ (void)dprintf(STDERR_FILENO, "\n");
}
/*ARGSUSED*/