]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/fd-util.h
Merge pull request #19533 from yuwata/network-queue
[thirdparty/systemd.git] / src / basic / fd-util.h
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 #pragma once
3
4 #include <dirent.h>
5 #include <stdbool.h>
6 #include <stdio.h>
7 #include <sys/socket.h>
8
9 #include "macro.h"
10
11 /* maximum length of fdname */
12 #define FDNAME_MAX 255
13
14 /* Make sure we can distinguish fd 0 and NULL */
15 #define FD_TO_PTR(fd) INT_TO_PTR((fd)+1)
16 #define PTR_TO_FD(p) (PTR_TO_INT(p)-1)
17
18 int close_nointr(int fd);
19 int safe_close(int fd);
20 void safe_close_pair(int p[static 2]);
21
22 static inline int safe_close_above_stdio(int fd) {
23 if (fd < 3) /* Don't close stdin/stdout/stderr, but still invalidate the fd by returning -1 */
24 return -1;
25
26 return safe_close(fd);
27 }
28
29 void close_many(const int fds[], size_t n_fd);
30
31 int fclose_nointr(FILE *f);
32 FILE* safe_fclose(FILE *f);
33 DIR* safe_closedir(DIR *f);
34
35 static inline void closep(int *fd) {
36 safe_close(*fd);
37 }
38
39 static inline void close_pairp(int (*p)[2]) {
40 safe_close_pair(*p);
41 }
42
43 static inline void fclosep(FILE **f) {
44 safe_fclose(*f);
45 }
46
47 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, pclose, NULL);
48 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(DIR*, closedir, NULL);
49
50 #define _cleanup_close_ _cleanup_(closep)
51 #define _cleanup_fclose_ _cleanup_(fclosep)
52 #define _cleanup_pclose_ _cleanup_(pclosep)
53 #define _cleanup_closedir_ _cleanup_(closedirp)
54 #define _cleanup_close_pair_ _cleanup_(close_pairp)
55
56 int fd_nonblock(int fd, bool nonblock);
57 int fd_cloexec(int fd, bool cloexec);
58
59 int close_all_fds(const int except[], size_t n_except);
60
61 int same_fd(int a, int b);
62
63 void cmsg_close_all(struct msghdr *mh);
64
65 bool fdname_is_valid(const char *s);
66
67 int fd_get_path(int fd, char **ret);
68
69 int move_fd(int from, int to, int cloexec);
70
71 enum {
72 ACQUIRE_NO_DEV_NULL = 1 << 0,
73 ACQUIRE_NO_MEMFD = 1 << 1,
74 ACQUIRE_NO_PIPE = 1 << 2,
75 ACQUIRE_NO_TMPFILE = 1 << 3,
76 ACQUIRE_NO_REGULAR = 1 << 4,
77 };
78
79 int acquire_data_fd(const void *data, size_t size, unsigned flags);
80
81 int fd_duplicate_data_fd(int fd);
82
83 int fd_move_above_stdio(int fd);
84
85 int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd);
86
87 static inline int make_null_stdio(void) {
88 return rearrange_stdio(-1, -1, -1);
89 }
90
91 /* Like TAKE_PTR() but for file descriptors, resetting them to -1 */
92 #define TAKE_FD(fd) \
93 ({ \
94 int _fd_ = (fd); \
95 (fd) = -1; \
96 _fd_; \
97 })
98
99 /* Like free_and_replace(), but for file descriptors */
100 #define CLOSE_AND_REPLACE(a, b) \
101 ({ \
102 int *_fdp_ = &(a); \
103 safe_close(*_fdp_); \
104 *_fdp_ = TAKE_FD(b); \
105 0; \
106 })
107
108
109 int fd_reopen(int fd, int flags);
110
111 int read_nr_open(void);