]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/fdset.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
9 #include "alloc-util.h"
10 #include "dirent-util.h"
15 #include "parse-util.h"
16 #include "path-util.h"
19 #define MAKE_SET(s) ((Set*) s)
20 #define MAKE_FDSET(s) ((FDSet*) s)
22 FDSet
*fdset_new(void) {
23 return MAKE_FDSET(set_new(NULL
));
26 int fdset_new_array(FDSet
**ret
, const int *fds
, size_t n_fds
) {
37 for (i
= 0; i
< n_fds
; i
++) {
39 r
= fdset_put(s
, fds
[i
]);
41 set_free(MAKE_SET(s
));
50 void fdset_close(FDSet
*s
) {
53 while ((p
= set_steal_first(MAKE_SET(s
)))) {
54 /* Valgrind's fd might have ended up in this set here, due to fdset_new_fill(). We'll ignore
55 * all failures here, so that the EBADFD that valgrind will return us on close() doesn't
58 /* When reloading duplicates of the private bus connection fds and suchlike are closed here,
59 * which has no effect at all, since they are only duplicates. So don't be surprised about
60 * these log messages. */
62 log_debug("Closing set fd %i", PTR_TO_FD(p
));
63 (void) close_nointr(PTR_TO_FD(p
));
67 FDSet
* fdset_free(FDSet
*s
) {
69 set_free(MAKE_SET(s
));
73 int fdset_put(FDSet
*s
, int fd
) {
77 return set_put(MAKE_SET(s
), FD_TO_PTR(fd
));
80 int fdset_put_dup(FDSet
*s
, int fd
) {
86 copy
= fcntl(fd
, F_DUPFD_CLOEXEC
, 3);
90 r
= fdset_put(s
, copy
);
99 bool fdset_contains(FDSet
*s
, int fd
) {
103 return !!set_get(MAKE_SET(s
), FD_TO_PTR(fd
));
106 int fdset_remove(FDSet
*s
, int fd
) {
110 return set_remove(MAKE_SET(s
), FD_TO_PTR(fd
)) ? fd
: -ENOENT
;
113 int fdset_new_fill(FDSet
**_s
) {
114 _cleanup_closedir_
DIR *d
= NULL
;
121 /* Creates an fdset and fills in all currently open file
124 d
= opendir("/proc/self/fd");
134 FOREACH_DIRENT(de
, d
, return -errno
) {
137 r
= safe_atoi(de
->d_name
, &fd
);
147 r
= fdset_put(s
, fd
);
156 /* We won't close the fds here! */
158 set_free(MAKE_SET(s
));
163 int fdset_cloexec(FDSet
*fds
, bool b
) {
170 SET_FOREACH(p
, MAKE_SET(fds
), i
) {
171 r
= fd_cloexec(PTR_TO_FD(p
), b
);
179 int fdset_new_listen_fds(FDSet
**_s
, bool unset
) {
185 /* Creates an fdset and fills in all passed file descriptors */
193 n
= sd_listen_fds(unset
);
194 for (fd
= SD_LISTEN_FDS_START
; fd
< SD_LISTEN_FDS_START
+ n
; fd
++) {
195 r
= fdset_put(s
, fd
);
205 set_free(MAKE_SET(s
));
210 int fdset_close_others(FDSet
*fds
) {
220 SET_FOREACH(e
, MAKE_SET(fds
), i
)
221 a
[j
++] = PTR_TO_FD(e
);
226 return close_all_fds(a
, j
);
229 unsigned fdset_size(FDSet
*fds
) {
230 return set_size(MAKE_SET(fds
));
233 bool fdset_isempty(FDSet
*fds
) {
234 return set_isempty(MAKE_SET(fds
));
237 int fdset_iterate(FDSet
*s
, Iterator
*i
) {
240 if (!set_iterate(MAKE_SET(s
), i
, &p
))
246 int fdset_steal_first(FDSet
*fds
) {
249 p
= set_steal_first(MAKE_SET(fds
));