diff options
Diffstat (limited to 'src/libudev')
-rw-r--r-- | src/libudev/util.c | 24 | ||||
-rw-r--r-- | src/libudev/util.h | 2 |
2 files changed, 26 insertions, 0 deletions
diff --git a/src/libudev/util.c b/src/libudev/util.c index 4796505a5c..cfdf848cce 100644 --- a/src/libudev/util.c +++ b/src/libudev/util.c @@ -154,6 +154,30 @@ void close_nointr_nofail(int fd) { assert_se(close_nointr(fd) == 0); } +int safe_close(int fd) { + + /* + * Like close_nointr() but cannot fail. Guarantees errno is + * unchanged. Is a NOP with negative fds passed, and returns + * -1, so that it can be used in this syntax: + * + * fd = safe_close(fd); + */ + + if (fd >= 0) { + PROTECT_ERRNO; + + /* The kernel might return pretty much any error code + * via close(), but the fd will be closed anyway. The + * only condition we want to check for here is whether + * the fd was invalid at all... */ + + assert_se(close_nointr(fd) != -EBADF); + } + + return -1; +} + int unlink_noerrno(const char *path) { PROTECT_ERRNO; int r; diff --git a/src/libudev/util.h b/src/libudev/util.h index a950f2658f..332dfb6207 100644 --- a/src/libudev/util.h +++ b/src/libudev/util.h @@ -124,6 +124,8 @@ static inline const char *startswith(const char *s, const char *prefix) { char *endswith(const char *s, const char *postfix) _pure_; int close_nointr(int fd); +int safe_close(int fd); + void close_nointr_nofail(int fd); int safe_atou(const char *s, unsigned *ret_u); |