]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/fdset.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include "alloc-util.h"
11 #include "dirent-util.h"
16 #include "parse-util.h"
17 #include "path-util.h"
20 #define MAKE_SET(s) ((Set*) s)
21 #define MAKE_FDSET(s) ((FDSet*) s)
23 FDSet
*fdset_new(void) {
24 return MAKE_FDSET(set_new(NULL
));
27 int fdset_new_array(FDSet
**ret
, const int *fds
, size_t n_fds
) {
38 for (i
= 0; i
< n_fds
; i
++) {
40 r
= fdset_put(s
, fds
[i
]);
42 set_free(MAKE_SET(s
));
51 FDSet
* fdset_free(FDSet
*s
) {
54 while ((p
= set_steal_first(MAKE_SET(s
)))) {
55 /* Valgrind's fd might have ended up in this set here,
56 * due to fdset_new_fill(). We'll ignore all failures
57 * here, so that the EBADFD that valgrind will return
58 * us on close() doesn't influence us */
60 /* When reloading duplicates of the private bus
61 * connection fds and suchlike are closed here, which
62 * has no effect at all, since they are only
63 * duplicates. So don't be surprised about these log
66 log_debug("Closing left-over fd %i", PTR_TO_FD(p
));
67 close_nointr(PTR_TO_FD(p
));
70 set_free(MAKE_SET(s
));
74 int fdset_put(FDSet
*s
, int fd
) {
78 return set_put(MAKE_SET(s
), FD_TO_PTR(fd
));
81 int fdset_put_dup(FDSet
*s
, int fd
) {
87 copy
= fcntl(fd
, F_DUPFD_CLOEXEC
, 3);
91 r
= fdset_put(s
, copy
);
100 bool fdset_contains(FDSet
*s
, int fd
) {
104 return !!set_get(MAKE_SET(s
), FD_TO_PTR(fd
));
107 int fdset_remove(FDSet
*s
, int fd
) {
111 return set_remove(MAKE_SET(s
), FD_TO_PTR(fd
)) ? fd
: -ENOENT
;
114 int fdset_new_fill(FDSet
**_s
) {
115 _cleanup_closedir_
DIR *d
= NULL
;
122 /* Creates an fdset and fills in all currently open file
125 d
= opendir("/proc/self/fd");
135 FOREACH_DIRENT(de
, d
, return -errno
) {
138 r
= safe_atoi(de
->d_name
, &fd
);
148 r
= fdset_put(s
, fd
);
157 /* We won't close the fds here! */
159 set_free(MAKE_SET(s
));
164 int fdset_cloexec(FDSet
*fds
, bool b
) {
171 SET_FOREACH(p
, MAKE_SET(fds
), i
) {
172 r
= fd_cloexec(PTR_TO_FD(p
), b
);
180 int fdset_new_listen_fds(FDSet
**_s
, bool unset
) {
186 /* Creates an fdset and fills in all passed file descriptors */
194 n
= sd_listen_fds(unset
);
195 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ n
; fd
++) {
196 r
= fdset_put(s
, fd
);
206 set_free(MAKE_SET(s
));
211 int fdset_close_others(FDSet
*fds
) {
219 SET_FOREACH(e
, MAKE_SET(fds
), i
)
220 a
[j
++] = PTR_TO_FD(e
);
224 return close_all_fds(a
, j
);
227 unsigned fdset_size(FDSet
*fds
) {
228 return set_size(MAKE_SET(fds
));
231 bool fdset_isempty(FDSet
*fds
) {
232 return set_isempty(MAKE_SET(fds
));
235 int fdset_iterate(FDSet
*s
, Iterator
*i
) {
238 if (!set_iterate(MAKE_SET(s
), i
, &p
))
244 int fdset_steal_first(FDSet
*fds
) {
247 p
= set_steal_first(MAKE_SET(fds
));