summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/basic/fd-util.c27
-rw-r--r--src/basic/fd-util.h2
-rw-r--r--src/test/test-fs-util.c6
3 files changed, 23 insertions, 12 deletions
diff --git a/src/basic/fd-util.c b/src/basic/fd-util.c
index 8ae79fb69..21c9d8b87 100644
--- a/src/basic/fd-util.c
+++ b/src/basic/fd-util.c
@@ -431,7 +431,6 @@ int move_fd(int from, int to, int cloexec) {
int acquire_data_fd(const void *data, size_t size, unsigned flags) {
- char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
_cleanup_close_pair_ int pipefds[2] = { -1, -1 };
char pattern[] = "/dev/shm/data-fd-XXXXXX";
_cleanup_close_ int fd = -1;
@@ -541,12 +540,7 @@ try_dev_shm:
return -EIO;
/* Let's reopen the thing, in order to get an O_RDONLY fd for the original O_RDWR one */
- xsprintf(procfs_path, "/proc/self/fd/%i", fd);
- r = open(procfs_path, O_RDONLY|O_CLOEXEC);
- if (r < 0)
- return -errno;
-
- return r;
+ return fd_reopen(fd, O_RDONLY|O_CLOEXEC);
}
try_dev_shm_without_o_tmpfile:
@@ -729,3 +723,22 @@ finish:
return r;
}
+
+int fd_reopen(int fd, int flags) {
+ char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
+ int new_fd;
+
+ /* Reopens the specified fd with new flags. This is useful for convert an O_PATH fd into a regular one, or to
+ * turn O_RDWR fds into O_RDONLY fds.
+ *
+ * This doesn't work on sockets (since they cannot be open()ed, ever).
+ *
+ * This implicitly resets the file read index to 0. */
+
+ xsprintf(procfs_path, "/proc/self/fd/%i", fd);
+ new_fd = open(procfs_path, flags);
+ if (new_fd < 0)
+ return -errno;
+
+ return new_fd;
+}
diff --git a/src/basic/fd-util.h b/src/basic/fd-util.h
index cb4677ec4..0f5a950f1 100644
--- a/src/basic/fd-util.h
+++ b/src/basic/fd-util.h
@@ -117,3 +117,5 @@ static inline int make_null_stdio(void) {
(fd) = -1; \
_fd_; \
})
+
+int fd_reopen(int fd, int flags);
diff --git a/src/test/test-fs-util.c b/src/test/test-fs-util.c
index ba01eea4e..35bb699c3 100644
--- a/src/test/test-fs-util.c
+++ b/src/test/test-fs-util.c
@@ -270,17 +270,13 @@ static void test_chase_symlinks(void) {
pfd = chase_symlinks(p, NULL, CHASE_OPEN, NULL);
if (pfd != -ENOENT) {
- char procfs[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(pfd) + 1];
_cleanup_close_ int fd = -1;
sd_id128_t a, b;
assert_se(pfd >= 0);
- xsprintf(procfs, "/proc/self/fd/%i", pfd);
-
- fd = open(procfs, O_RDONLY|O_CLOEXEC);
+ fd = fd_reopen(pfd, O_RDONLY|O_CLOEXEC);
assert_se(fd >= 0);
-
safe_close(pfd);
assert_se(id128_read_fd(fd, ID128_PLAIN, &a) >= 0);