Passing file descriptors

Josiah Carlson jcarlson at uci.edu
Thu Jun 10 02:08:16 EDT 2004


I forgot to post the script...


  - Josiah

-----clip here-----

#!/usr/pd/bin/python
#
# fdpass.py

#
# Example of passing an open filedescriptor with Python. Will only work
# on UNIX dialects that support the I_SENDFD and I_RECVFD ioctl() calls.
#

import  fcntl, os, sys, struct, socket

#
# fork() off!
#
(pRead, pWrite) = os.pipe()

pid = os.fork()


if pid != 0:

     # We're in the parent.

     # Open a file for passing along to child. Use own source code,
     # which is guaranteed to exist. :)

     fileObj = open('./fdpass.py', 'r')

     # ioctl() will only pass raw filedescriptors. Find fd of fileObj.
     fd = fileObj.fileno()

     # Send to the child using ioctl().
     try:

         retval = fcntl.ioctl(pWrite, 1, fd)

         # Should probably check retval rather than just printing it. :)
         print "Parent ioctl() returned %d" % retval
     except Exception, e:
         print e

     # Wait for child to terminate, then exit.
     os.waitpid(pid, 0)
     sys.exit(0)

else:
     import time
     time.sleep(1)
     # We're in the child.

     # Create a string representing the strrecvfd structure that ioctl()
     # will return.
     s = struct.pack('iii', 0, 0, 0)

     # Receive filedescriptor. Will block until descriptor is sent.
     ret = fcntl.ioctl(pRead, 1, s)

     # Unpack the strrecvfd-structure that ioctl() should return.
     # fd is the filedescriptor, uid/gid the user/group id of the
     # sending stream.
     (fd, uid, gid) = struct.unpack('iii', ret)

     # Reopen the filedescriptor as a Python File-object.
     fileObj = os.fdopen(fd, 'r')

     # Example usage: Read file, print the first line.
     lines = fileObj.readlines()
     print lines[0],
     sys.exit(0)




More information about the Python-list mailing list