commit 6a9bf206cfe09ef7d9121cd6c87b345d44d48a43
parent 9d33ba1104b390256f72f8203212720b95447b38
Author: NRK <nrk@disroot.org>
Date: Sun, 5 Jan 2025 22:20:00 +0000
don't feed unchecked fd to dup2()
the open() might fail and then dup2 will be called with -1 fd.
clang-tidy complains about this.
just open "/dev/null" once at program startup, check the result,
and then reuse that fd throughout.
Diffstat:
1 file changed, 10 insertions(+), 6 deletions(-)
diff --git a/src/nnn.c b/src/nnn.c
@@ -438,6 +438,7 @@ static int nselected;
#ifndef NOFIFO
static int fifofd = -1;
#endif
+static int devnullfd = -1;
static time_t gtimesecs;
static uint_t idletimeout, selbufpos, selbuflen;
static ushort_t xlines, xcols;
@@ -2487,13 +2488,10 @@ static int spawn(char *file, char *arg1, char *arg2, char *arg3, ushort_t flag)
if (pid == 0) {
/* Suppress stdout and stderr */
if (flag & F_NOTRACE) {
- int fd = open("/dev/null", O_WRONLY, 0200);
-
if (flag & F_NOSTDIN)
- dup2(fd, STDIN_FILENO);
- dup2(fd, STDOUT_FILENO); // NOLINT
- dup2(fd, STDERR_FILENO);
- close(fd);
+ dup2(devnullfd, STDIN_FILENO);
+ dup2(devnullfd, STDOUT_FILENO);
+ dup2(devnullfd, STDERR_FILENO);
} else if (flag & F_TTY) {
/* If stdout has been redirected to a non-tty, force output to tty */
if (!isatty(STDOUT_FILENO)) {
@@ -8859,6 +8857,12 @@ int main(int argc, char *argv[])
DPRINTF_S(VERSION);
#endif
+ devnullfd = open("/dev/null", O_RDWR | O_CLOEXEC);
+ if (devnullfd < 0) {
+ xerror();
+ return EXIT_FAILURE;
+ }
+
/* Prefix for temporary files */
if (!set_tmp_path())
return EXIT_FAILURE;