Skip to content

Commit 835a4fc

Browse files
committed
Ensure fd 0 stdin </dev/null is always inheritable.
When gunicorn --daemon daemonizes the process, prior to this change it was noted that in the general case (without -R / --enable-stdio-inheritance), when fd 0 was replaced with /dev/null, the dup2 copy is skipped, and per PEP 446 "Make newly created file descriptors non-inheritable", the result was a stdio fd </dev/null which was non-inheritable. As a result, any launched subprocess did not have an open 0/stdin fd, which can cause problems in some applications. This change retains the behaviour of opening /dev/null with fd 0, but adds a call to os.set_inheritable(..) to ensure the fd is inheritable. The -R branch had different logic but has now been standardised with the general case. It was previously opening /dev/null as fd 3 and the dup2() copy made it inheritable as fd 0. This branch now applies the same logic: open as fd 0 (i.e. after close(0)), then set_inheritable. As a result, an extra fd 3 </dev/null previously left open is no longer left open. Signed-off-by: Brett Randall <[email protected]>
1 parent e5a9715 commit 835a4fc

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

gunicorn/util.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -486,21 +486,28 @@ def daemonize(enable_stdio_inheritance=False):
486486
closerange(0, 3)
487487

488488
fd_null = os.open(REDIRECT_TO, os.O_RDWR)
489+
# PEP 446, make fd for /dev/null inheritable
490+
os.set_inheritable(fd_null, True)
489491

492+
# expect fd_null to be always 0 here, but in-case not ...
490493
if fd_null != 0:
491494
os.dup2(fd_null, 0)
492495

493496
os.dup2(fd_null, 1)
494497
os.dup2(fd_null, 2)
495498

496499
else:
497-
fd_null = os.open(REDIRECT_TO, os.O_RDWR)
498-
499500
# Always redirect stdin to /dev/null as we would
500501
# never expect to need to read interactive input.
501502

503+
os.close(0)
504+
505+
fd_null = os.open(REDIRECT_TO, os.O_RDWR)
506+
# PEP 446, make fd for /dev/null inheritable
507+
os.set_inheritable(fd_null, True)
508+
509+
# expect fd_null to be always 0 here, but in-case not ...
502510
if fd_null != 0:
503-
os.close(0)
504511
os.dup2(fd_null, 0)
505512

506513
# If stdout and stderr are still connected to

0 commit comments

Comments
 (0)