|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 Atym, Inc. |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + * |
| 6 | + * This sample application is roughly based on the sample code in Linux |
| 7 | + * manpage for timerfd(). |
| 8 | + */ |
| 9 | +#include <sys/timerfd.h> |
| 10 | +#include <unistd.h> |
| 11 | +#include <stdlib.h> |
| 12 | +#include <stdio.h> |
| 13 | +#include <stdint.h> |
| 14 | +#include <inttypes.h> |
| 15 | + |
| 16 | +#define fatal(msg) \ |
| 17 | + do { perror(msg); exit(EXIT_FAILURE); } while (0) |
| 18 | + |
| 19 | +void read_now(int fd) |
| 20 | +{ |
| 21 | + uint64_t count; |
| 22 | + |
| 23 | + /* read the number of times the timer has expired */ |
| 24 | + int bytes_read = read(fd, &count, sizeof(count)); |
| 25 | + if (bytes_read == -1) { |
| 26 | + fatal("read"); |
| 27 | + } |
| 28 | + printf("Timer expired %" PRIu64 " times\n", count); |
| 29 | +} |
| 30 | + |
| 31 | +int main(void) |
| 32 | +{ |
| 33 | + /* create the timer file descriptor */ |
| 34 | + int tfd = timerfd_create(0, 0); |
| 35 | + if (tfd == -1) { |
| 36 | + fatal("timerfd_create"); |
| 37 | + } |
| 38 | + |
| 39 | + /* arm a recurring timer for 1 second */ |
| 40 | + struct itimerspec timer_spec = { |
| 41 | + .it_interval = { .tv_sec = 1, .tv_nsec = 0 }, |
| 42 | + .it_value = { .tv_sec = 1, .tv_nsec = 0 } |
| 43 | + }; |
| 44 | + |
| 45 | + int rc = timerfd_settime(tfd, 0, &timer_spec, NULL); |
| 46 | + |
| 47 | + if (rc == -1) { |
| 48 | + fatal("timerfd_settime"); |
| 49 | + } |
| 50 | + |
| 51 | + /* read the number of times the timer has expired */ |
| 52 | + /* will block until the timer expires */ |
| 53 | + read_now(tfd); |
| 54 | + |
| 55 | + /* if we wait long enough, the timer will expire more than once */ |
| 56 | + sleep(3); |
| 57 | + |
| 58 | + /* the function will not block as the timer already expired */ |
| 59 | + read_now(tfd); |
| 60 | + |
| 61 | + close(tfd); |
| 62 | + |
| 63 | + printf("Timer closed\n"); |
| 64 | + |
| 65 | + return 0; |
| 66 | +} |
0 commit comments