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.
This commit is contained in:
committed by
Luca Boccassi
parent
05bda20f07
commit
b839101aac
+3
-10
@@ -381,22 +381,15 @@ int parse_env_file_fd_sentinel(
|
||||
const char *fname, /* only used for logging */
|
||||
...) {
|
||||
|
||||
_cleanup_close_ int fd_ro = -EBADF;
|
||||
_cleanup_fclose_ FILE *f = NULL;
|
||||
va_list ap;
|
||||
int r;
|
||||
|
||||
assert(fd >= 0);
|
||||
|
||||
fd_ro = fd_reopen(fd, O_CLOEXEC | O_RDONLY);
|
||||
if (fd_ro < 0)
|
||||
return fd_ro;
|
||||
|
||||
f = fdopen(fd_ro, "re");
|
||||
if (!f)
|
||||
return -errno;
|
||||
|
||||
TAKE_FD(fd_ro);
|
||||
r = fdopen_independent(fd, "re", &f);
|
||||
if (r < 0)
|
||||
return r;
|
||||
|
||||
va_start(ap, fname);
|
||||
r = parse_env_filev(f, fname, ap);
|
||||
|
||||
@@ -1020,6 +1020,35 @@ int xfopenat(int dir_fd, const char *path, const char *mode, int flags, FILE **r
|
||||
return 0;
|
||||
}
|
||||
|
||||
int fdopen_independent(int fd, const char *mode, FILE **ret) {
|
||||
_cleanup_close_ int copy_fd = -EBADF;
|
||||
_cleanup_fclose_ FILE *f = NULL;
|
||||
int mode_flags;
|
||||
|
||||
assert(fd >= 0);
|
||||
assert(mode);
|
||||
assert(ret);
|
||||
|
||||
/* A combination of fdopen() + fd_reopen(). i.e. reopens the inode the specified fd points to and
|
||||
* returns a FILE* for it */
|
||||
|
||||
mode_flags = fopen_mode_to_flags(mode);
|
||||
if (mode_flags < 0)
|
||||
return mode_flags;
|
||||
|
||||
copy_fd = fd_reopen(fd, mode_flags);
|
||||
if (copy_fd < 0)
|
||||
return copy_fd;
|
||||
|
||||
f = fdopen(copy_fd, mode);
|
||||
if (!f)
|
||||
return -errno;
|
||||
|
||||
TAKE_FD(copy_fd);
|
||||
*ret = TAKE_PTR(f);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int search_and_fopen_internal(
|
||||
const char *path,
|
||||
const char *mode,
|
||||
|
||||
@@ -106,6 +106,8 @@ int get_proc_field(const char *filename, const char *pattern, const char *termin
|
||||
DIR *xopendirat(int dirfd, const char *name, int flags);
|
||||
int xfopenat(int dir_fd, const char *path, const char *mode, int flags, FILE **ret);
|
||||
|
||||
int fdopen_independent(int fd, const char *mode, FILE **ret);
|
||||
|
||||
int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **ret, char **ret_path);
|
||||
int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **ret, char **ret_path);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user