From 80ac731c907c04f60148a696162cb95d7cedc90a Mon Sep 17 00:00:00 2001 From: Tavian Barnes Date: Thu, 1 Oct 2020 10:09:05 -0400 Subject: util: Move redirect() and isopen() to main.c --- main.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'main.c') diff --git a/main.c b/main.c index 70f4d8b..f77d787 100644 --- a/main.c +++ b/main.c @@ -60,6 +60,28 @@ #include #include +/** + * Check if a file descriptor is open. + */ +static bool isopen(int fd) { + return fcntl(fd, F_GETFD) >= 0 || errno != EBADF; +} + +/** + * 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); + } + + return ret; +} + /** * Make sure the standard streams std{in,out,err} are open. If they are not, * future open() calls may use those file descriptors, and std{in,out,err} will -- cgit v1.2.3