From c9fcb25f51db9ae67f9585c93924e5af8b8bb8b8 Mon Sep 17 00:00:00 2001 From: benoitc Date: Sun, 21 Apr 2013 11:57:38 +0200 Subject: [PATCH] add GUNICORN_INHERIT_FDS environment variable support You can now pass a list of file descriptors to Gunicorn that won't be closed when it starts. Allows someone to pass any stream to gunicorn or set some redirection. --- gunicorn/util.py | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/gunicorn/util.py b/gunicorn/util.py index 4c0c0ea6..457b9e1b 100644 --- a/gunicorn/util.py +++ b/gunicorn/util.py @@ -411,11 +411,32 @@ def daemonize(): os.umask(0) maxfd = get_maxfd() - closerange(0, maxfd) + + fds = [] + if 'GUNICORN_INHERIT_FDS' in os.environ: + list_fds = os.environ['GUNICORN_INHERIT_FDS'].split(',') + try: + fds = [int(fd) for fd in list_fds] + except ValueError: + raise RuntimeError("Bad value in 'GUNICORN_INHERIT_FDS'") + + for fd in range(0, max_fd): + if fd in fds: + continue + + try: + os.close(fd) + except OSError: # ERROR, fd wasn't open to begin with (ignored) + pass + else: + closerange(0, maxfd) os.open(REDIRECT_TO, os.O_RDWR) - os.dup2(0, 1) - os.dup2(0, 2) + if 1 not in fds: + os.dup2(0, 1) + + if 2 not in fds: + os.dup2(0, 2) def seed():