summaryrefslogtreecommitdiff
path: root/src/test/test-fileio.c
diff options
context:
space:
mode:
authorLennart Poettering <lennart@poettering.net>2023-03-23 12:33:41 +0100
committerLuca Boccassi <luca.boccassi@gmail.com>2023-03-23 22:48:00 +0000
commitb839101aacb38131f0f4313b1b76316e663e58e9 (patch)
tree0bd0c0442cddfb1dc8adcad384f269224c37f98c /src/test/test-fileio.c
parent05bda20f073947b77423faca68ef360df5bfa464 (diff)
downloadsystemd-b839101aacb38131f0f4313b1b76316e663e58e9.tar.gz
fileio: add new helper fdopen_independent()
This is a combination of fdopen() and fd_reopen(). i.e. it first reopens the fd, and then converts that into a FILE*. We do this at various places already manually. let's move this into a helper call of its own.
Diffstat (limited to 'src/test/test-fileio.c')
-rw-r--r--src/test/test-fileio.c43
1 files changed, 43 insertions, 0 deletions
diff --git a/src/test/test-fileio.c b/src/test/test-fileio.c
index 2e05992c18..1a9a8a5ddc 100644
--- a/src/test/test-fileio.c
+++ b/src/test/test-fileio.c
@@ -14,6 +14,7 @@
#include "fileio.h"
#include "fs-util.h"
#include "io-util.h"
+#include "memfd-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "process-util.h"
@@ -1072,4 +1073,46 @@ TEST(test_read_virtual_file) {
test_read_virtual_file_one(SIZE_MAX);
}
+TEST(test_fdopen_independent) {
+#define TEST_TEXT "this is some random test text we are going to write to a memfd"
+ _cleanup_close_ int fd = -EBADF;
+ _cleanup_fclose_ FILE *f = NULL;
+ char buf[STRLEN(TEST_TEXT) + 1];
+
+ fd = memfd_new("fdopen_independent");
+ if (fd < 0) {
+ assert_se(ERRNO_IS_NOT_SUPPORTED(fd));
+ return;
+ }
+
+ assert_se(write(fd, TEST_TEXT, strlen(TEST_TEXT)) == strlen(TEST_TEXT));
+ /* we'll leave the read offset at the end of the memfd, the fdopen_independent() descriptors should
+ * start at the beginning anyway */
+
+ assert_se(fdopen_independent(fd, "re", &f) >= 0);
+ zero(buf);
+ assert_se(fread(buf, 1, sizeof(buf), f) == strlen(TEST_TEXT));
+ assert_se(streq(buf, TEST_TEXT));
+ assert_se((fcntl(fileno(f), F_GETFL) & O_ACCMODE) == O_RDONLY);
+ assert_se(FLAGS_SET(fcntl(fileno(f), F_GETFD), FD_CLOEXEC));
+ f = safe_fclose(f);
+
+ assert_se(fdopen_independent(fd, "r", &f) >= 0);
+ zero(buf);
+ assert_se(fread(buf, 1, sizeof(buf), f) == strlen(TEST_TEXT));
+ assert_se(streq(buf, TEST_TEXT));
+ assert_se((fcntl(fileno(f), F_GETFL) & O_ACCMODE) == O_RDONLY);
+ assert_se(!FLAGS_SET(fcntl(fileno(f), F_GETFD), FD_CLOEXEC));
+ f = safe_fclose(f);
+
+ assert_se(fdopen_independent(fd, "r+e", &f) >= 0);
+ zero(buf);
+ assert_se(fread(buf, 1, sizeof(buf), f) == strlen(TEST_TEXT));
+ assert_se(streq(buf, TEST_TEXT));
+ assert_se((fcntl(fileno(f), F_GETFL) & O_ACCMODE) == O_RDWR);
+ assert_se(FLAGS_SET(fcntl(fileno(f), F_GETFD), FD_CLOEXEC));
+ f = safe_fclose(f);
+}
+
+
DEFINE_TEST_MAIN(LOG_DEBUG);