From 74ca738f6a01fb5fc19c5c3899f5cb1fdc1d7f68 Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Wed, 9 Sep 2015 15:20:10 +0200 Subject: util: introduce safe_fclose() and port everything over to it Adds a coccinelle script to port things over automatically. --- src/basic/util.c | 27 +++++++++++++++++++++++++++ src/basic/util.h | 8 +++++++- 2 files changed, 34 insertions(+), 1 deletion(-) (limited to 'src/basic') diff --git a/src/basic/util.c b/src/basic/util.c index 3e41e6ad41..f7b2edf88c 100644 --- a/src/basic/util.c +++ b/src/basic/util.c @@ -327,6 +327,33 @@ void close_many(const int fds[], unsigned n_fd) { safe_close(fds[i]); } +int fclose_nointr(FILE *f) { + assert(f); + + /* Same as close_nointr(), but for fclose() */ + + if (fclose(f) == 0) + return 0; + + if (errno == EINTR) + return 0; + + return -errno; +} + +FILE* safe_fclose(FILE *f) { + + /* Same as safe_close(), but for fclose() */ + + if (f) { + PROTECT_ERRNO; + + assert_se(fclose_nointr(f) != EBADF); + } + + return NULL; +} + int unlink_noerrno(const char *path) { PROTECT_ERRNO; int r; diff --git a/src/basic/util.h b/src/basic/util.h index 0fafebd52d..48567756b9 100644 --- a/src/basic/util.h +++ b/src/basic/util.h @@ -149,6 +149,9 @@ void safe_close_pair(int p[]); void close_many(const int fds[], unsigned n_fd); +int fclose_nointr(FILE *f); +FILE* safe_fclose(FILE *f); + int parse_size(const char *t, off_t base, off_t *size); int parse_boolean(const char *v) _pure_; @@ -514,7 +517,10 @@ static inline void close_pairp(int (*p)[2]) { safe_close_pair(*p); } -DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, fclose); +static inline void fclosep(FILE **f) { + safe_fclose(*f); +} + DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, pclose); DEFINE_TRIVIAL_CLEANUP_FUNC(DIR*, closedir); DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, endmntent); -- cgit v1.2.3-54-g00ecf