2022-03-25 14:11:44 +00:00
|
|
|
#if 0
|
|
|
|
/*─────────────────────────────────────────────────────────────────╗
|
|
|
|
│ To the extent possible under law, Justine Tunney has waived │
|
|
|
|
│ all copyright and related or neighboring rights to this file, │
|
|
|
|
│ as it is written in the following disclaimers: │
|
|
|
|
│ • http://unlicense.org/ │
|
|
|
|
│ • http://creativecommons.org/publicdomain/zero/1.0/ │
|
|
|
|
╚─────────────────────────────────────────────────────────────────*/
|
|
|
|
#endif
|
2024-09-11 09:14:38 +00:00
|
|
|
#include <assert.h>
|
|
|
|
#include <signal.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <sys/time.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @fileoverview interval timer tutorial
|
|
|
|
*/
|
2022-03-25 14:11:44 +00:00
|
|
|
|
|
|
|
volatile bool gotalrm;
|
|
|
|
|
2022-09-02 12:08:35 +00:00
|
|
|
void OnSigAlrm(int sig, siginfo_t *si, void *ctx) {
|
2022-03-25 14:11:44 +00:00
|
|
|
gotalrm = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
|
|
|
|
//////////////////////////////////////////////////////////////////////////////
|
|
|
|
printf("first tutorial: set singleshot alarm for 1.5 seconds from now\n");
|
|
|
|
|
|
|
|
// setup alarm in 1.5 seconds
|
|
|
|
// this timer tears itself down once it's handled
|
|
|
|
struct itimerval shot = {{0, 0}, {1, 500000}};
|
|
|
|
struct sigaction handler = {.sa_sigaction = OnSigAlrm,
|
|
|
|
.sa_flags = SA_RESETHAND | SA_SIGINFO};
|
2023-10-12 04:38:27 +00:00
|
|
|
unassert(!sigaction(SIGALRM, &handler, 0));
|
|
|
|
unassert(!setitimer(ITIMER_REAL, &shot, 0));
|
2022-03-25 14:11:44 +00:00
|
|
|
|
|
|
|
// wait for alarm
|
|
|
|
pause();
|
|
|
|
printf("got singleshot alarm!\n\n");
|
|
|
|
|
|
|
|
//////////////////////////////////////////////////////////////////////////////
|
|
|
|
printf("second tutorial: interval timer\n");
|
|
|
|
|
|
|
|
// setup timer every 1.5 seconds
|
|
|
|
struct sigaction oldalrm;
|
|
|
|
struct sigaction sigalrm = {.sa_sigaction = OnSigAlrm,
|
|
|
|
.sa_flags = SA_SIGINFO};
|
2023-10-12 04:38:27 +00:00
|
|
|
unassert(!sigaction(SIGALRM, &sigalrm, &oldalrm));
|
2022-03-25 14:11:44 +00:00
|
|
|
struct itimerval oldtimer;
|
|
|
|
struct itimerval timer = {{1, 500000}, {1, 500000}};
|
2023-10-12 04:38:27 +00:00
|
|
|
unassert(!setitimer(ITIMER_REAL, &timer, &oldtimer));
|
2022-03-25 14:11:44 +00:00
|
|
|
|
|
|
|
// wait for three timeouts
|
|
|
|
int i = 0;
|
|
|
|
int n = 3;
|
|
|
|
while (i < n) {
|
|
|
|
pause();
|
|
|
|
if (gotalrm) {
|
|
|
|
++i;
|
|
|
|
printf("got timeout %d out of %d\n", i, n);
|
|
|
|
gotalrm = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// teardown timer
|
2023-10-12 04:38:27 +00:00
|
|
|
unassert(!setitimer(ITIMER_REAL, &oldtimer, 0));
|
|
|
|
unassert(!sigaction(SIGALRM, &oldalrm, 0));
|
2022-03-25 14:11:44 +00:00
|
|
|
}
|