Skip to content

Commit

Permalink
don't feed unchecked fd to dup2()
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
N-R-K committed Jan 5, 2025
1 parent c3f22c5 commit 919f1fa
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/nnn.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit 919f1fa

Please sign in to comment.