Skip to content
Open
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/unix_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -887,8 +887,8 @@ def _do_wait(self, pid, pidfd, callback, args):
pid)
else:
returncode = waitstatus_to_exitcode(status)

os.close(pidfd)
finally:
os.close(pidfd)
callback(pid, returncode, *args)

class _ThreadedChildWatcher:
Expand Down
40 changes: 40 additions & 0 deletions Lib/test/test_asyncio/test_unix_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -1333,5 +1333,45 @@ async def child_main():

self.assertEqual(result.value, 0)


@unittest.skipUnless(
unix_events.can_use_pidfd(),
"operating system does not support pidfd",
)
class PidfdChildWatcherTests(test_utils.TestCase):

def setUp(self):
super().setUp()
self.loop = asyncio.new_event_loop()
self.set_event_loop(self.loop)

def test_pidfd_closed_when_waitpid_raises(self):
# _do_wait() must close the pidfd even when waitpid()
# fails with something other than ChildProcessError, otherwise the
# pidfd is leaked
self.loop.set_exception_handler(lambda loop, context: None)

async def coro():
before = os_helper.fd_count()
proc = await asyncio.create_subprocess_exec(
sys.executable, '-c', 'import sys; sys.stdin.read()',
stdin=asyncio.subprocess.PIPE
)

with mock.patch.object(os, 'waitpid',
side_effect=OSError('unexpected')) as m:
proc.stdin.close()
while not m.called:
await asyncio.sleep(0)

os.waitpid(proc.pid, 0)
proc._transport._process_exited(0)
await proc.wait()

self.assertEqual(os_helper.fd_count(), before)

self.loop.run_until_complete(coro())


if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a pidfd leak in ``_PidfdChildWatcher`` on Linux: the watcher no
longer leaks the process file descriptor when ``waitpid()`` fails with an
error other than :exc:`ChildProcessError`.
Loading