]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
fileio: introduce take_fdopen{_unlocked}() variant
authorVito Caputo <vcaputo@pengaru.com>
Tue, 31 Mar 2020 07:49:07 +0000 (00:49 -0700)
committerVito Caputo <vcaputo@pengaru.com>
Tue, 31 Mar 2020 13:48:00 +0000 (06:48 -0700)
With the addition of _cleanup_close_ there's a repetitious
pattern of assigning -1 to the fd after a successful fdopen
to prevent its close on cleanup now that the FILE * owns the
fd.

This introduces a wrapper that instead takes a pointer to the
fd being opened, and always overwrites the fd with -1 on success.

A future commit will cleanup all the fdopen call sites to use the
wrapper and elide the manual -1 fd assignment.

src/basic/fileio.c
src/basic/fileio.h

index fe0c4f4707141a2dfd90ebce10500067c44064a8..c82a9d2c01dee6f704be0e54d37cf76246d1554f 100644 (file)
@@ -54,6 +54,32 @@ int fdopen_unlocked(int fd, const char *options, FILE **ret) {
         return 0;
 }
 
+int take_fdopen_unlocked(int *fd, const char *options, FILE **ret) {
+        int     r;
+
+        assert(fd);
+
+        r = fdopen_unlocked(*fd, options, ret);
+        if (r < 0)
+                return r;
+
+        *fd = -1;
+
+        return 0;
+}
+
+FILE* take_fdopen(int *fd, const char *options) {
+        assert(fd);
+
+        FILE *f = fdopen(*fd, options);
+        if (!f)
+                return NULL;
+
+        *fd = -1;
+
+        return f;
+}
+
 FILE* open_memstream_unlocked(char **ptr, size_t *sizeloc) {
         FILE *f = open_memstream(ptr, sizeloc);
         if (!f)
index e6fea2afd4b7d612ce6443dcd050fa79a6dd7b59..525f6ac814a1f48f51489ac5e91609c1532dffd8 100644 (file)
@@ -39,6 +39,8 @@ typedef enum {
 
 int fopen_unlocked(const char *path, const char *options, FILE **ret);
 int fdopen_unlocked(int fd, const char *options, FILE **ret);
+int take_fdopen_unlocked(int *fd, const char *options, FILE **ret);
+FILE* take_fdopen(int *fd, const char *options);
 FILE* open_memstream_unlocked(char **ptr, size_t *sizeloc);
 FILE* fmemopen_unlocked(void *buf, size_t size, const char *mode);