How to close all files between fork and exec?

Phil Mayers p.mayers at obfuscate.ic.ac.uk
Wed Jan 17 10:15:19 EST 2001


You've got two choices:

1) If you know what file handles you'll have open always (you don't 
inherit any, and you open all the ones you use) you can set the 
close-on-exec flag like this:

     import fcntl
     import FCNTL

     st = fcntl.fcntl(fd, FCNTL.F_GETFD)
     if flag==1:
         fcntl.fcntl(fd, FCNTL.F_SETFD, st | FCNTL.FD_CLOEXEC)
     elif flag==0:
         fcntl.fcntl(fd, FCNTL.F_SETFD, st & ~FCNTL.FD_CLOEXEC)
     else:
         raise TypeError, "usage: setfd_cloexec(fd[,flag]) flag = 0 | 1"

     return st

2) Use the sysconf module to get the "real" max open files. If there 
isn't a limit (stupid...) then go as high as you think is "reasonable" 
given the environment you're inheriting from.

Cheer,
Phil

Harald Kirsch wrote:

> Python has fork/exec. I want to use it. After fork and before exec I
> would like the child process to close all files other than 0, 1 and 2
> (i.e. standard input/output/error). 
> 
> On some systems there is a constant like OPEN_MAX but I read that on
> recent Solaris versions there is no real limit to it.
> How do I get hold of the highest numbered open file descriptor, in
> particular in python?
> 
>   Harald Kirsch




More information about the Python-list mailing list