diff options
author | cheloha <cheloha@cvs.openbsd.org> | 2020-06-06 17:03:17 +0000 |
---|---|---|
committer | cheloha <cheloha@cvs.openbsd.org> | 2020-06-06 17:03:17 +0000 |
commit | 6c19e921a2569462d799b4f4a6f13bd39a58d172 (patch) | |
tree | 1b6eb4c20d0dab7810f82e02c57323d020644600 /games/grdc/grdc.c | |
parent | 7487a718c27525156c91c65f134d9b51ef0250d7 (diff) |
grdc(6): implement timeout with alarm(3)
grdc(6) has an optional argument indicating a timeout in seconds.
For example, one could do:
$ grdc 60
to to tell grdc(6) to run for sixty seconds and then exit gracefully.
As implemented, however, the timeout may occur too early or too late
if the system clock is reset with settimeofday(2).
To avoid this problem we can instead use alarm(3) and a signal handler
to implement the timeout. alarm(3) is unaffected by settimeofday(2).
Diffstat (limited to 'games/grdc/grdc.c')
-rw-r--r-- | games/grdc/grdc.c | 29 |
1 files changed, 18 insertions, 11 deletions
diff --git a/games/grdc/grdc.c b/games/grdc/grdc.c index 7f62dc3ebdb..567e60d710a 100644 --- a/games/grdc/grdc.c +++ b/games/grdc/grdc.c @@ -1,4 +1,4 @@ -/* $OpenBSD: grdc.c,v 1.32 2020/06/06 13:21:40 cheloha Exp $ */ +/* $OpenBSD: grdc.c,v 1.33 2020/06/06 17:03:16 cheloha Exp $ */ /* * * Copyright 2002 Amos Shapir. Public domain. @@ -35,6 +35,7 @@ short disp[11] = { }; long old[6], next[6], new[6], mask; +volatile sig_atomic_t sigalrmed = 0; volatile sig_atomic_t sigtermed = 0; volatile sig_atomic_t sigwinched = 0; @@ -46,6 +47,12 @@ void standt(int); void __dead usage(void); void +sigalrm(int signo) +{ + sigalrmed = signo; +} + +void sighndl(int signo) { sigtermed = signo; @@ -63,8 +70,8 @@ main(int argc, char *argv[]) long t, a; int i, j, s, k, rv; int scrol; - int n = 0; - struct timespec delay, end; + unsigned int n = 0; + struct timespec delay; struct pollfd pfd; const char *errstr; long scroldelay = 50000000; @@ -92,7 +99,7 @@ main(int argc, char *argv[]) if (argc > 1) usage(); if (argc == 1) { - n = strtonum(*argv, 1, INT_MAX, &errstr); + n = strtonum(*argv, 1, UINT_MAX, &errstr); if (errstr) { warnx("number of seconds is %s", errstr); usage(); @@ -130,8 +137,10 @@ main(int argc, char *argv[]) sigwinched = 1; /* force initial sizing */ clock_gettime(CLOCK_REALTIME, &now); - if (n) - end.tv_sec = now.tv_sec + n - 1; + if (n) { + signal(SIGALRM, sigalrm); + alarm(n); + } do { if (sigwinched) { sigwinched = 0; @@ -235,10 +244,8 @@ main(int argc, char *argv[]) if (rv == 1) { char q = 0; read(STDIN_FILENO, &q, 1); - if (q == 'q') { - n = 1; - end.tv_sec = now.tv_sec; - } + if (q == 'q') + sigalrmed = 1; } now.tv_sec++; @@ -249,7 +256,7 @@ main(int argc, char *argv[]) endwin(); errx(1, "terminated by signal %d", sigtermed); } - } while (n == 0 || now.tv_sec < end.tv_sec); + } while (!sigalrmed); standend(); clear(); refresh(); |