Skip to content

Commit 01a202a

Browse files
FFY00gpshead
andauthored
bpo-40550: Fix time-of-check/time-of-action issue in subprocess.Popen.send_signal. (pythonGH-20010)
send_signal() now swallows the exception if the process it thought was still alive winds up not to exist anymore (always a plausible race condition despite the checks). Co-authored-by: Gregory P. Smith <greg@krypto.org>
1 parent 3172936 commit 01a202a

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

Lib/subprocess.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -2078,7 +2078,11 @@ def send_signal(self, sig):
20782078
# The race condition can still happen if the race condition
20792079
# described above happens between the returncode test
20802080
# and the kill() call.
2081-
os.kill(self.pid, sig)
2081+
try:
2082+
os.kill(self.pid, sig)
2083+
except ProcessLookupError:
2084+
# Supress the race condition error; bpo-40550.
2085+
pass
20822086

20832087
def terminate(self):
20842088
"""Terminate the process with SIGTERM

Lib/test/test_subprocess.py

+13
Original file line numberDiff line numberDiff line change
@@ -3229,6 +3229,19 @@ def test_send_signal_race(self):
32293229
# so Popen failed to read it and uses a default returncode instead.
32303230
self.assertIsNotNone(proc.returncode)
32313231

3232+
def test_send_signal_race2(self):
3233+
# bpo-40550: the process might exist between the returncode check and
3234+
# the kill operation
3235+
p = subprocess.Popen([sys.executable, '-c', 'exit(1)'])
3236+
3237+
# wait for process to exit
3238+
while not p.returncode:
3239+
p.poll()
3240+
3241+
with mock.patch.object(p, 'poll', new=lambda: None):
3242+
p.returncode = None
3243+
p.send_signal(signal.SIGTERM)
3244+
32323245
def test_communicate_repeated_call_after_stdout_close(self):
32333246
proc = subprocess.Popen([sys.executable, '-c',
32343247
'import os, time; os.close(1), time.sleep(2)'],
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix time-of-check/time-of-action issue in subprocess.Popen.send_signal.

0 commit comments

Comments
 (0)