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.
This commit is contained in:
NRK 2025-01-05 22:20:00 +00:00
parent 9d33ba1104
commit 6a9bf206cf

View file

@ -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;