views:

276

answers:

2

Python's subprocess module by default passes all open file descriptors to any child processes it spawns. This means that if the parent process is listening on a port, and is killed, it cannot restart and begin listening again (even using SO_REUSEADDR) because the child is still in possession of that descriptor. I have no control over the child process.

The subprocess POpen constructor does accept a close_fds argument, which would close descriptors on the child, just as I want. However, there is a restriction, only on Windows, that prevents it from being used if stdin/stdout are also overridden, which I need to do.

Does anyone know of a work-around for this on Windows?

A: 

I don't have a windows box around, so this is untested, but I'd be tempted to try the os.dup and os.dup2 methods; duplicate the file descriptors and use those instead of the parent ones.

Charlie Martin
I'm not sure I understand; which descriptors would I duplicate, and how/where would I be using them?
DNS
A `dup`'ed file descriptor worsens things. He needs the equivalent of the Linux O_CLOEXEC flag, which AFAIK does not exist on Windows.
ΤΖΩΤΖΙΟΥ
+1  A: 

What seems to be the most relevant information that I can find: SetHandleInformation, referenced in this article, should give you pointers.

You'll probably need to use pywin32 and/or ctypes to accomplish what you want.

ΤΖΩΤΖΙΟΥ