fork/exec & close file descriptors

Jon Ribbens jon+usenet at unequivocal.co.uk
Tue May 19 10:32:33 EDT 2015


On 2015-05-19, Skip Montanaro <skip.montanaro at gmail.com> wrote:
> Yeah, I'm still on 2.7, and am aware of PEP 446. Note that many of the file
> descriptors will not have been created by my Python code. They will have
> been created by underlying C/C++ libraries, so I can't guarantee which
> flags were set on file open.

There is no portable way to do this, the problem is Unix not Python.
The below code is a reasonable stab at it, but there is no 100%
guaranteed method. The code is untested but you get the idea.


  import errno
  import os


  def closeall(min=0, max=4096, keep=frozenset()):
      """Close all open file descriptors except for the given exceptions.

      Any file descriptors below or equal to `min`, or in the set `keep`
      will not be closed. Any file descriptors above `max` *might* not be
      closed.
      """
      # First try /proc/$$/pid
      try:
          for fd in os.listdir("/proc/%d/fd" % (os.getpid())):
	      try:
		  fd = int(fd)
              except ValueError:
	          continue
	      if fd >= min and fd not in keep:
	          os.close(int(fd))
          return
      except OSError as exc:
          if exc[0] != errno.ENOENT:
	      raise
      # If /proc was not available, fall back to closing a lot of descriptors.
      for fd in range(min, max):
          if fd not in keep:
	      try:
		  os.close(fd)
	      except OSError as exc:
		  if exc[0] != errno.EBADF:
		      raise



More information about the Python-list mailing list