]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
fdset: add new helper to convert an fdset to an array
authorLennart Poettering <lennart@poettering.net>
Tue, 28 Mar 2023 09:17:23 +0000 (11:17 +0200)
committerLennart Poettering <lennart@poettering.net>
Wed, 29 Mar 2023 17:09:10 +0000 (19:09 +0200)
src/shared/fdset.c
src/shared/fdset.h

index 4427c1ce680bda4b2dcc829354dbbcb760b01c00..49928b66d6e749869eb4a5d9483225b846ebf17b 100644 (file)
@@ -192,24 +192,43 @@ int fdset_new_listen_fds(FDSet **ret, bool unset) {
         return 0;
 }
 
-int fdset_close_others(FDSet *fds) {
-        _cleanup_free_ int *a = NULL;
-        size_t j = 0, m;
+int fdset_to_array(FDSet *fds, int **ret) {
+        unsigned j = 0, m;
         void *e;
+        int *a;
 
-        m = fdset_size(fds);
-        if (m > 0) {
-                a = new(int, m);
-                if (!a)
-                        return -ENOMEM;
+        assert(ret);
 
-                SET_FOREACH(e, MAKE_SET(fds))
-                        a[j++] = PTR_TO_FD(e);
+        m = fdset_size(fds);
+        if (m > INT_MAX) /* We want to be able to return an "int" */
+                return -ENOMEM;
+        if (m == 0) {
+                *ret = NULL; /* suppress array allocation if empty */
+                return 0;
         }
 
+        a = new(int, m);
+        if (!a)
+                return -ENOMEM;
+
+        SET_FOREACH(e, MAKE_SET(fds))
+                a[j++] = PTR_TO_FD(e);
+
         assert(j == m);
 
-        return close_all_fds(a, j);
+        *ret = TAKE_PTR(a);
+        return (int) m;
+}
+
+int fdset_close_others(FDSet *fds) {
+        _cleanup_free_ int *a = NULL;
+        int n;
+
+        n = fdset_to_array(fds, &a);
+        if (n < 0)
+                return n;
+
+        return close_all_fds(a, n);
 }
 
 unsigned fdset_size(FDSet *fds) {
index 39d15ee4aaf076b14312221a054deb8b90d535ba..0e55db81b432507ff9c24b11e8f0eb8a1fcd87c2 100644 (file)
@@ -24,6 +24,8 @@ int fdset_new_listen_fds(FDSet **ret, bool unset);
 
 int fdset_cloexec(FDSet *fds, bool b);
 
+int fdset_to_array(FDSet *fds, int **ret);
+
 int fdset_close_others(FDSet *fds);
 
 unsigned fdset_size(FDSet *fds);