util: add new safe_close_above_stdio() wrapper

At various places we only want to close fds if they are not
stdin/stdout/stderr, i.e. fds 0, 1, 2. Let's add a unified helper call
for that, and port everything over.
This commit is contained in:
Lennart Poettering
2018-02-28 10:00:50 +01:00
parent c7f9a8d270
commit e7685a77b4
7 changed files with 50 additions and 21 deletions
+7
View File
@@ -35,6 +35,13 @@ int close_nointr(int fd);
int safe_close(int fd);
void safe_close_pair(int p[]);
static inline int safe_close_above_stdio(int fd) {
if (fd < 3) /* Don't close stdin/stdout/stderr, but still invalidate the fd by returning -1 */
return -1;
return safe_close(fd);
}
void close_many(const int fds[], unsigned n_fd);
int fclose_nointr(FILE *f);
+1 -8
View File
@@ -94,14 +94,7 @@ static char *log_abort_msg = NULL;
} while (false)
static void log_close_console(void) {
if (console_fd < 0)
return;
if (console_fd >= 3)
safe_close(console_fd);
console_fd = -1;
console_fd = safe_close_above_stdio(console_fd);
}
static int log_open_console(void) {
+1 -2
View File
@@ -1428,8 +1428,7 @@ int fork_agent(const char *name, const int except[], unsigned n_except, pid_t *r
_exit(EXIT_FAILURE);
}
if (fd > STDERR_FILENO)
close(fd);
safe_close_above_stdio(fd);
}
/* Count arguments */
+1 -2
View File
@@ -917,8 +917,7 @@ int make_stdio(int fd) {
if (dup2(fd, STDERR_FILENO) < 0 && r >= 0)
r = -errno;
if (fd >= 3)
safe_close(fd);
safe_close_above_stdio(fd);
/* Explicitly unset O_CLOEXEC, since if fd was < 3, then dup2() was a NOP and the bit hence possibly set. */
stdio_unset_cloexec();