From aba396d4c56136483722c9ed67e86c3325330a80 Mon Sep 17 00:00:00 2001 From: David Wilson Date: Sun, 10 Mar 2019 18:56:40 +0000 Subject: [PATCH] core: bootstrap FD management improvements - open fd 0/1/2 with correct file mode - trap reserve_tty_fd in a file object, since all other FD manual FD management is going away. --- mitogen/core.py | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/mitogen/core.py b/mitogen/core.py index 0935abcb..dacdb444 100644 --- a/mitogen/core.py +++ b/mitogen/core.py @@ -3381,16 +3381,13 @@ class ExternalContext(object): def _nullify_stdio(self): """ - Open /dev/null to replace stdin, and stdout/stderr temporarily. In case - of odd startup, assume we may be allocated a standard handle. + Open /dev/null to replace stdio temporarily. In case of odd startup, + assume we may be allocated a standard handle. """ - fd = os.open('/dev/null', os.O_RDWR) - try: - for stdfd in (0, 1, 2): - if fd != stdfd: - os.dup2(fd, stdfd) - finally: - if fd not in (0, 1, 2): + for stdfd, mode in ((0, os.O_RDONLY), (1, os.O_RDWR), (2, os.O_RDWR)): + fd = os.open('/dev/null', mode) + if fd != stdfd: + os.dup2(fd, stdfd) os.close(fd) def _setup_stdio(self): @@ -3402,10 +3399,11 @@ class ExternalContext(object): # around a permanent dup() to avoid receiving SIGHUP. try: if os.isatty(2): - self.reserve_tty_fd = os.dup(2) - set_cloexec(self.reserve_tty_fd) + self.reserve_tty_fp = os.fdopen(os.dup(2), 'r+b', 0) + set_cloexec(self.reserve_tty_fp) except OSError: pass + # When sys.stdout was opened by the runtime, overwriting it will not # close FD 1. However when forking from a child that previously used # fdopen(), overwriting it /will/ close FD 1. So we must swallow the