diff --git a/glnx-dirfd.c b/glnx-dirfd.c index ea12c8f9deb852739a72c031006cd2d0430e75e6..e6c3319c1b876edbabd88e808aea5468bb158d9c 100644 --- a/glnx-dirfd.c +++ b/glnx-dirfd.c @@ -382,8 +382,7 @@ _glnx_tmpdir_free (GLnxTmpDir *tmpd, if (!(tmpd && tmpd->initialized)) return TRUE; g_assert_cmpint (tmpd->fd, !=, -1); - (void) close (tmpd->fd); - tmpd->fd = -1; + glnx_close_fd (&tmpd->fd); g_assert (tmpd->path); g_assert_cmpint (tmpd->src_dfd, !=, -1); g_autofree char *path = tmpd->path; /* Take ownership */ diff --git a/glnx-local-alloc.h b/glnx-local-alloc.h index 46dd9d25d7c377af5bc2de61a1b13ad0798f89ec..3be1fa43b02b4a7a383c39c3770fdd8803d012a3 100644 --- a/glnx-local-alloc.h +++ b/glnx-local-alloc.h @@ -42,14 +42,30 @@ glnx_local_obj_unref (void *v) } #define glnx_unref_object __attribute__ ((cleanup(glnx_local_obj_unref))) +static inline int +glnx_steal_fd (int *fdp) +{ + int fd = *fdp; + *fdp = -1; + return fd; +} + +/** + * glnx_close_fd: + * @fdp: Pointer to fd + * + * Effectively `close (glnx_steal_fd (&fd))`. Also + * asserts that `close()` did not raise `EBADF` - encountering + * that error is usually a critical bug in the program. + */ static inline void -glnx_cleanup_close_fdp (int *fdp) +glnx_close_fd (int *fdp) { - int fd, errsv; + int errsv; g_assert (fdp); - fd = *fdp; + int fd = glnx_steal_fd (fdp); if (fd >= 0) { errsv = errno; @@ -62,16 +78,14 @@ glnx_cleanup_close_fdp (int *fdp) /** * glnx_fd_close: * + * Deprecated in favor of `glnx_autofd`. + */ +#define glnx_fd_close __attribute__((cleanup(glnx_close_fd))) +/** + * glnx_autofd: + * * Call close() on a variable location when it goes out of scope. */ -#define glnx_fd_close __attribute__((cleanup(glnx_cleanup_close_fdp))) - -static inline int -glnx_steal_fd (int *fdp) -{ - int fd = *fdp; - *fdp = -1; - return fd; -} +#define glnx_autofd __attribute__((cleanup(glnx_close_fd))) G_END_DECLS diff --git a/glnx-lockfile.c b/glnx-lockfile.c index cd5c978c616546ccbe60db8cb49816b47b2725e9..2956edafe0557e0cd877150c57b30ab484695f62 100644 --- a/glnx-lockfile.c +++ b/glnx-lockfile.c @@ -119,8 +119,7 @@ glnx_make_lock_file(int dfd, const char *p, int operation, GLnxLockFile *out_loc if (st.st_nlink > 0) break; - (void) close(fd); - fd = -1; + glnx_close_fd (&fd); } /* Note that if this is not AT_FDCWD, the caller takes responsibility @@ -174,9 +173,7 @@ void glnx_release_lock_file(GLnxLockFile *f) { f->path = NULL; } - if (f->fd != -1) - (void) close (f->fd); - f->fd = -1; + glnx_close_fd (&f->fd); f->operation = 0; f->initialized = FALSE; }