From 958d591c888a4b9ab457ae414ef120dae77ee589 Mon Sep 17 00:00:00 2001 From: Tavian Barnes Date: Thu, 1 Oct 2020 10:24:40 -0400 Subject: main: Preserve errno over close() in redirect() --- main.c | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/main.c b/main.c index f77d787..2d6649e 100644 --- a/main.c +++ b/main.c @@ -71,14 +71,15 @@ static bool isopen(int fd) { * Open a file and redirect it to a particular descriptor. */ static int redirect(int fd, const char *path, int flags) { - int ret = open(path, flags); - - if (ret >= 0 && ret != fd) { - int orig = ret; - ret = dup2(orig, fd); - close(orig); + int newfd = open(path, flags); + if (newfd < 0 || newfd == fd) { + return newfd; } + int ret = dup2(newfd, fd); + int err = errno; + close(newfd); + errno = err; return ret; } -- cgit v1.2.3