From dd9a26715dc212a02c8aa8637067f7585c3f12e4 Mon Sep 17 00:00:00 2001 From: Aaron Gyes Date: Sun, 7 Apr 2019 13:54:33 -0700 Subject: [PATCH] fcntl a little less Setting O_CLOEXEC on closed file descriptors and getting E_BADF should be faster than actually checking if an fd is open first. --- src/fish.cpp | 7 ++++--- src/wutil.cpp | 11 +++-------- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/fish.cpp b/src/fish.cpp index 21832b265..4b0f2c2c8 100644 --- a/src/fish.cpp +++ b/src/fish.cpp @@ -401,13 +401,14 @@ int main(int argc, char **argv) { res = reader_read(STDIN_FILENO, {}); } else { char *file = *(argv + (my_optind++)); +#if defined(O_CLOEXEC) + int fd = open(file, O_RDONLY | O_CLOEXEC); +#else int fd = open(file, O_RDONLY); +#endif if (fd == -1) { perror(file); } else { - // OK to not do this atomically since we cannot have gone multithreaded yet. - set_cloexec(fd); - wcstring_list_t list; for (char **ptr = argv + my_optind; *ptr; ptr++) { list.push_back(str2wcstring(*ptr)); diff --git a/src/wutil.cpp b/src/wutil.cpp index fa250c59b..5813334e8 100644 --- a/src/wutil.cpp +++ b/src/wutil.cpp @@ -176,14 +176,9 @@ FILE *wfopen(const wcstring &path, const char *mode) { } bool set_cloexec(int fd) { - int flags = fcntl(fd, F_GETFD, 0); - if (flags < 0) { - return false; - } - if (flags & FD_CLOEXEC) { - return true; - } - return fcntl(fd, F_SETFD, flags | FD_CLOEXEC) >= 0; + int flags = fcntl(fd, F_SETFD, flags | FD_CLOEXEC); + if (flags == -1) return false; + return true; } static int wopen_internal(const wcstring &pathname, int flags, mode_t mode, bool cloexec) {