From c4afc3d5c0a392cc04ce162fa5992f17c7ea7da3 Mon Sep 17 00:00:00 2001 From: David Herrmann Date: Fri, 25 Sep 2015 12:49:44 +0200 Subject: [PATCH] shared: add safe_close() Add safe_close() helper that makes close(2) a bit nicer to use. This also introduces PROTECT_ERRNO, which makes sure a function does not clutter errno if called. Signed-off-by: David Herrmann --- src/shared-macro.h | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/shared-macro.h b/src/shared-macro.h index c542b75f..56fa7d10 100644 --- a/src/shared-macro.h +++ b/src/shared-macro.h @@ -27,6 +27,7 @@ #include #include +#include #include #include #include @@ -34,6 +35,7 @@ #include #include #include +#include /* * We require: @@ -72,6 +74,15 @@ #define _weak_ __attribute__((weak)) #define _weakref_(_x) __attribute__((weakref(#_x))) +/* + * PROTECT_ERRNO: make sure a function protects errno + */ +static inline void reset_errno(int *saved_errno) +{ + errno = *saved_errno; +} +#define PROTECT_ERRNO _cleanup_(reset_errno) _unused_ int saved_errno = errno + /* * DEFINE_TRIVIAL_CLEANUP_FUNC() - define helper suitable for _cleanup_() * @_type: type of object to cleanup @@ -126,6 +137,22 @@ static inline void *mfree(void *mem) return NULL; } +/* + * safe_close() - safe variant of close(2) + * @fd: fd to close + * + * This is the same as close(2), but allows passing negative FDs, which makes + * it a no-op. Furthermore, this always returns -1. + */ +static inline int safe_close(int fd) +{ + if (fd >= 0) { + PROTECT_ERRNO; + close(fd); + } + return -1; +} + /* * Miscellaneous cleanup helpers * All these helpers are suitable for use with _cleanup_(). They call the helper @@ -136,6 +163,11 @@ static inline void freep(void *p) free(*(void**)p); } +static inline void safe_closep(int *fd) +{ + safe_close(*fd); +} + /* * streq() - test whether two strings are equal * @_a: string A