From ad3a28c5f2520d0688730aa83eaee815fb9a5762 Mon Sep 17 00:00:00 2001 From: Colin Walters Date: Wed, 17 Dec 2014 22:28:58 -0500 Subject: localalloc: Add gs_fd_close cleanup Now that we're encouraging use of openat(), fds are a lot more prevalent. --- src/gsystem-local-alloc.h | 19 +++++++++++++++++++ tests/localalloc.c | 2 ++ 2 files changed, 21 insertions(+) diff --git a/src/gsystem-local-alloc.h b/src/gsystem-local-alloc.h index 71f444b..51b6251 100644 --- a/src/gsystem-local-alloc.h +++ b/src/gsystem-local-alloc.h @@ -184,6 +184,25 @@ GS_DEFINE_CLEANUP_FUNCTION0(GError*, gs_local_free_error, g_error_free) #define gs_unref_keyfile __attribute__ ((cleanup(gs_local_keyfile_unref))) GS_DEFINE_CLEANUP_FUNCTION0(GKeyFile*, gs_local_keyfile_unref, g_key_file_unref) +static inline void +gs_cleanup_close_fdp (int *fdp) +{ + int fd; + + g_assert (fdp); + + fd = *fdp; + if (fd != -1) + (void) close (fd); +} + +/** + * gs_fd_close: + * + * Call close() on a variable location when it goes out of scope. + */ +#define gs_fd_close __attribute__((cleanup(gs_cleanup_close_fdp))) + G_END_DECLS #endif diff --git a/tests/localalloc.c b/tests/localalloc.c index 46024c3..087261a 100644 --- a/tests/localalloc.c +++ b/tests/localalloc.c @@ -25,6 +25,8 @@ test_localalloc (void) gs_strfreev char **strv = g_get_environ (); gs_free_error GError *err = g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED, "oops %s", "darn!"); gs_unref_keyfile GKeyFile *keyfile = g_key_file_new (); + gs_fd_close int fd = open ("/dev/null", O_RDONLY); + gs_fd_close int fd2 = -1; } int -- cgit v1.2.1