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
39 changes: 39 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,44 @@ 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
watcher = unix_events._PidfdChildWatcher()
pid = os.posix_spawn(sys.executable, [sys.executable, '-c', ''],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer to have a real test which uses asyncio's APIs for creating the process than os

os.environ)
pidfd = os.pidfd_open(pid)
try:
async def coro():
with mock.patch.object(os, 'waitpid',
side_effect=OSError('unexpected')):
with self.assertRaises(OSError):
watcher._do_wait(pid, pidfd, lambda *a: None, ())

self.loop.run_until_complete(coro())

with self.assertRaises(OSError):
os.fstat(pidfd)
finally:
try:
os.close(pidfd)
except OSError:
pass
os.waitpid(pid, 0)


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