Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top