Skip to content

subprocess: close pipes/fds by using ExitStack #11686

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 29, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 18 additions & 17 deletions Lib/subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
import sys
import threading
import warnings
import contextlib
from time import monotonic as _time


Expand Down Expand Up @@ -1072,28 +1073,28 @@ def _close_pipe_fds(self,
# self._devnull is not always defined.
devnull_fd = getattr(self, '_devnull', None)

if _mswindows:
if p2cread != -1:
p2cread.Close()
if c2pwrite != -1:
c2pwrite.Close()
if errwrite != -1:
errwrite.Close()
else:
if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:
os.close(p2cread)
if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:
os.close(c2pwrite)
if errwrite != -1 and errread != -1 and errwrite != devnull_fd:
os.close(errwrite)
with contextlib.ExitStack() as stack:
if _mswindows:
if p2cread != -1:
stack.callback(p2cread.Close)
if c2pwrite != -1:
stack.callback(c2pwrite.Close)
if errwrite != -1:
stack.callback(errwrite.Close)
else:
if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:
stack.callback(os.close, p2cread)
if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:
stack.callback(os.close, c2pwrite)
if errwrite != -1 and errread != -1 and errwrite != devnull_fd:
stack.callback(os.close, errwrite)

if devnull_fd is not None:
os.close(devnull_fd)
if devnull_fd is not None:
stack.callback(os.close, devnull_fd)

# Prevent a double close of these handles/fds from __init__ on error.
self._closed_child_pipe_fds = True


if _mswindows:
#
# Windows methods
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
An ExitStack is now used internally within subprocess.POpen to clean up pipe
file handles. No behavior change in normal operation. But if closing one
handle were ever to cause an exception, the others will now be closed
instead of leaked. (patch by Giampaolo Rodola)