Skip to content
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
4 changes: 2 additions & 2 deletions Lib/asyncio/base_subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ def _try_finish(self):
# to avoid hanging forever in self._wait as otherwise _exit_waiters
# would never be woken up, we wake them up here.
for waiter in self._exit_waiters:
if not waiter.cancelled():
if not waiter.done():
waiter.set_result(self._returncode)
if all(p is not None and p.disconnected
for p in self._pipes.values()):
Expand All @@ -278,7 +278,7 @@ def _call_connection_lost(self, exc):
finally:
# wake up futures waiting for wait()
for waiter in self._exit_waiters:
if not waiter.cancelled():
if not waiter.done():
waiter.set_result(self._returncode)
self._exit_waiters = None
self._loop = None
Expand Down
31 changes: 31 additions & 0 deletions Lib/test/test_asyncio/test_subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,37 @@ def test_subprocess_repr(self):
)
transport.close()

def test_proc_exited_no_invalid_state_error_on_exit_waiters(self):
# gh-145541: when _connect_pipes hasn't completed (so
# _pipes_connected is False) and the process exits, _try_finish()
# sets the result on exit waiters. Then _call_connection_lost() must
# not call set_result() again on the same waiters.
self.loop.set_exception_handler(
lambda loop, context: self.fail(
f"unexpected exception: {context}")
)
waiter = self.loop.create_future()
transport, protocol = self.create_transport(waiter)

# Simulate a waiter registered via _wait() before the process exits.
exit_waiter = self.loop.create_future()
transport._exit_waiters.append(exit_waiter)

# _connect_pipes hasn't completed, so _pipes_connected is False.
self.assertFalse(transport._pipes_connected)

# Simulate process exit. _try_finish() will set the result on
# exit_waiter because _pipes_connected is False, and then schedule
# _call_connection_lost() because _pipes is empty (vacuously all
# disconnected). _call_connection_lost() must skip exit_waiter
# because it's already done.
transport._process_exited(6)
self.loop.run_until_complete(waiter)

self.assertEqual(exit_waiter.result(), 6)

transport.close()


class SubprocessMixin:

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix InvalidStateError when cancelling process created by :func:`asyncio.create_subprocess_exec` or :func:`asyncio.create_subprocess_shell`. Patch by Daan De Meyer.
Loading