]> git.ipfire.org Git - fireperf.git/commitdiff
main: Refactor setting up the timer
authorMichael Tremer <michael.tremer@ipfire.org>
Thu, 19 Sep 2024 09:31:35 +0000 (09:31 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Thu, 19 Sep 2024 09:31:35 +0000 (09:31 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/main.c

index 6ab10e2250ccbf0187642dee35fbeeed6d1768ce..7e47afda1170d386afeb551d9a2c9707e2dae3dd 100644 (file)
 #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);