diff --git a/Lib/asyncio/subprocess.py b/Lib/asyncio/subprocess.py index 26d7b755105c9d5..f3e853213db6baf 100644 --- a/Lib/asyncio/subprocess.py +++ b/Lib/asyncio/subprocess.py @@ -112,7 +112,8 @@ def _maybe_close_transport(self): def _get_close_waiter(self, stream): if stream is self.stdin: - return self._stdin_closed + # Cancellation of one waiter must not cancel the shared future. + return tasks.shield(self._stdin_closed) class Process: diff --git a/Lib/test/test_asyncio/test_subprocess_wait_closed.py b/Lib/test/test_asyncio/test_subprocess_wait_closed.py new file mode 100644 index 000000000000000..b634d8141a446f4 --- /dev/null +++ b/Lib/test/test_asyncio/test_subprocess_wait_closed.py @@ -0,0 +1,32 @@ +import asyncio +import sys +import unittest + + +class SubprocessWaitClosedTests(unittest.IsolatedAsyncioTestCase): + + async def test_cancel_one_stdin_close_waiter(self): + loop = asyncio.get_running_loop() + errors = [] + loop.set_exception_handler(lambda loop, context: errors.append(context)) + proc = await asyncio.create_subprocess_exec( + sys.executable, "-c", "import sys; sys.stdin.buffer.read()", + stdin=asyncio.subprocess.PIPE, + ) + stdin = proc.stdin + try: + cancelled = asyncio.create_task(stdin.wait_closed()) + remaining = asyncio.create_task(stdin.wait_closed()) + await asyncio.sleep(0) + cancelled.cancel() + with self.assertRaises(asyncio.CancelledError): + await cancelled + + stdin.close() + await remaining + await stdin.wait_closed() + finally: + stdin.close() + await proc.wait() + self.assertEqual(proc.returncode, 0) + self.assertEqual(errors, [])