Skip to content

Commit d61ec16

Browse files
authored
Merge pull request ceph#50622 from cofractal/close-range
common: use close_range on Linux Reviewed-by: Radoslaw Zarzynski <[email protected]>
2 parents f0dda24 + 1a33cef commit d61ec16

File tree

2 files changed

+29
-11
lines changed

2 files changed

+29
-11
lines changed

src/common/SubProcess.cc

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
#include <sys/types.h>
55
#include <signal.h>
66
#endif
7+
#ifdef __linux__
8+
#include <sys/syscall.h>
9+
#endif
710
#include <stdarg.h>
811
#include <fcntl.h>
912
#include <unistd.h>
@@ -200,6 +203,12 @@ int SubProcess::spawn() {
200203
int maxfd = sysconf(_SC_OPEN_MAX);
201204
if (maxfd == -1)
202205
maxfd = 16384;
206+
207+
#if defined(__linux__) && defined(SYS_close_range)
208+
if (::syscall(SYS_close_range, STDERR_FILENO + 1, ~0U, 0) == 0)
209+
maxfd = STDERR_FILENO;
210+
#endif
211+
203212
for (int fd = 0; fd <= maxfd; fd++) {
204213
if (fd == STDIN_FILENO && stdin_op != CLOSE)
205214
continue;

src/common/fork_function.h

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313
#ifndef _WIN32
1414
#include <sys/wait.h>
1515
#endif
16+
#ifdef __linux__
17+
#include <sys/syscall.h>
18+
#endif
1619
#include <sys/types.h>
1720

1821
#include "include/ceph_assert.h"
@@ -53,17 +56,23 @@ static inline int fork_function(
5356
// we are forker (first child)
5457

5558
// close all fds
56-
int maxfd = sysconf(_SC_OPEN_MAX);
57-
if (maxfd == -1)
58-
maxfd = 16384;
59-
for (int fd = 0; fd <= maxfd; fd++) {
60-
if (fd == STDIN_FILENO)
61-
continue;
62-
if (fd == STDOUT_FILENO)
63-
continue;
64-
if (fd == STDERR_FILENO)
65-
continue;
66-
::close(fd);
59+
#if defined(__linux__) && defined(SYS_close_range)
60+
if (::syscall(SYS_close_range, STDERR_FILENO + 1, ~0U, 0))
61+
#endif
62+
{
63+
// fall back to manually closing
64+
int maxfd = sysconf(_SC_OPEN_MAX);
65+
if (maxfd == -1)
66+
maxfd = 16384;
67+
for (int fd = 0; fd <= maxfd; fd++) {
68+
if (fd == STDIN_FILENO)
69+
continue;
70+
if (fd == STDOUT_FILENO)
71+
continue;
72+
if (fd == STDERR_FILENO)
73+
continue;
74+
::close(fd);
75+
}
6776
}
6877

6978
sigset_t mask, oldmask;

0 commit comments

Comments
 (0)