fork/exec & close file descriptors

Chris Angelico rosuav at gmail.com
Tue May 19 09:33:33 EDT 2015


On Tue, May 19, 2015 at 10:59 PM, Skip Montanaro
<skip.montanaro at gmail.com> wrote:
> Due to presumed bugs in an underlying library over which I have no control,
> I'm considering a restart in the wee hours of the morning. The basic
> fork/exec dance is not a problem, but how do I discover all the open file
> descriptors in the new child process to make sure they get closed? Do I
> simply start at fd 3 and call os.close() on everything up to some largish fd
> number? Some of these file descriptors will have been opened by stuff well
> below the Python level, so I don't know them a priori.

What Python version are you targeting? Are you aware of PEP 446?

https://www.python.org/dev/peps/pep-0446/

tl;dr: As of Python 3.4, the default is to close file descriptors on
exec automatically - and atomically, where possible.

I'm not sure if there's a 2.7 backport available, though even if there
is, you'll need to manually set your files non-inheritable; AIUI the
default in 2.7 can't be changed for backward compatibility reasons
(the change in 3.4 *will* break code that was relying on automatic
inheritability of FDs - they now have to be explicitly tagged).

ChrisA



More information about the Python-list mailing list