From: Michael Tremer Date: Thu, 19 Sep 2024 09:31:35 +0000 (+0000) Subject: main: Refactor setting up the timer X-Git-Url: http://git.ipfire.org/gitweb/gitweb.cgi?a=commitdiff_plain;h=0e30abd9dbce44fb3b5bfa6a1f761d06fb9c2918;p=fireperf.git main: Refactor setting up the timer Signed-off-by: Michael Tremer --- diff --git a/src/main.c b/src/main.c index 6ab10e2..7e47afd 100644 --- a/src/main.c +++ b/src/main.c @@ -35,6 +35,39 @@ #include "server.h" #include "stats.h" +static int setup_timer(struct fireperf_ctx* ctx, int epollfd) { + int timerfd = -1; + int r; + + // Create timerfd() + timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC); + if (timerfd < 0) + return -errno; + + struct epoll_event ev = { + .events = EPOLLIN, + .data.fd = timerfd, + }; + + // Register the timer with the event loop + r = epoll_ctl(epollfd, EPOLL_CTL_ADD, timerfd, &ev); + if (r) + return -errno; + + // Let the timer ping us once a second + struct itimerspec timer = { + .it_interval.tv_sec = 1, + .it_value.tv_sec = 1, + }; + + // Arm the timer + r = timerfd_settime(timerfd, 0, &timer, NULL); + if (r) + return -errno; + + return timerfd; +} + static int set_limits(struct fireperf_ctx* ctx) { struct rlimit limit; @@ -85,35 +118,10 @@ int main(int argc, char* argv[]) { goto ERROR; } - // Create timerfd() to print statistics - timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC); + // Create a timer that fires once a second + timerfd = setup_timer(ctx, epollfd); if (timerfd < 0) { - ERROR(ctx, "timerfd_create() failed: %s\n", strerror(errno)); - r = 1; - goto ERROR; - } - - struct epoll_event ev = { - .events = EPOLLIN, - .data.fd = timerfd, - }; - - if (epoll_ctl(epollfd, EPOLL_CTL_ADD, timerfd, &ev)) { - ERROR(ctx, "Could not add timerfd to epoll(): %s\n", strerror(errno)); - r = 1; - goto ERROR; - } - - // Let the timer ping us once a second - struct itimerspec timer = { - .it_interval.tv_sec = 1, - .it_value.tv_sec = 1, - }; - - r = timerfd_settime(timerfd, 0, &timer, NULL); - if (r) { - ERROR(ctx, "Could not set timer: %s\n", strerror(errno)); - r = 1; + ERROR(ctx, "Could not setup timer: %s\n", strerror(-r)); goto ERROR; } @@ -133,10 +141,8 @@ int main(int argc, char* argv[]) { ERROR: if (epollfd > 0) close(epollfd); - if (timerfd > 0) close(timerfd); - if (ctx) fireperf_ctx_free(ctx);