util: add xclose(fd) to close-and-reset an fd
authorPeter Hutterer <peter.hutterer@who-t.net>
Tue, 15 Oct 2024 01:52:12 +0000 (11:52 +1000)
committerMarge Bot <emma+marge@anholt.net>
Wed, 30 Oct 2024 23:20:42 +0000 (23:20 +0000)
This prevents accidentally leaving the fd set after closing.

And it includes the -1 check so we don't need this everywhere ourselves
(not that we use it right now but valgrind likes to complain about
this).

Part-of: <https://gitlab.freedesktop.org/libinput/libinput/-/merge_requests/1067>

src/util-files.h

index 15c5ab0d2a3704b028a8b3f8f44bdc69ddb9037e..e980d0991cf18e6b9e0283f0027ea6806fcb670d 100644 (file)
@@ -27,6 +27,7 @@
 
 #include <errno.h>
 #include <libgen.h>
+#include <unistd.h>
 #include <sys/stat.h>
 
 #include "util-strings.h"
@@ -52,3 +53,12 @@ mkdir_p(const char *dir)
 
        return (rc == -1 && errno != EEXIST) ? -errno : 0;
 }
+
+static inline void
+xclose(int *fd)
+{
+       if (*fd != -1) {
+               close(*fd);
+               *fd = -1;
+       }
+}