From 992e877614476dd40abd11a82ffedc6e261dabdf Mon Sep 17 00:00:00 2001 From: Helmut Grohne Date: Mon, 20 May 2024 12:01:59 +0200 Subject: add an asyncio waitid(P_PIDFD, ...) helper --- linuxnamespaces/__init__.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/linuxnamespaces/__init__.py b/linuxnamespaces/__init__.py index 1a8b0ee..3302867 100644 --- a/linuxnamespaces/__init__.py +++ b/linuxnamespaces/__init__.py @@ -673,3 +673,37 @@ def async_copyfd( ): return _AsyncSplicer(from_fd, to_fd, count).fut return _AsyncCopier(from_fd, to_fd, count).fut + + +class _AsyncPidfdWaiter: + def __init__(self, pidfd: int, flags: int): + self.pidfd = pidfd + self.flags = flags + self.loop = asyncio.get_running_loop() + self.fut: asyncio.Future[ + os.waitid_result | None + ] = self.loop.create_future() + self.loop.add_reader(pidfd, self.handle_readable) + + def handle_readable(self) -> None: + try: + result = os.waitid(os.P_PIDFD, self.pidfd, self.flags) + except OSError as err: + if err.errno != errno.EAGAIN: + self.loop.remove_reader(self.pidfd) + self.fut.set_exception(err) + except Exception as err: + self.loop.remove_reader(self.pidfd) + self.fut.set_exception(err) + else: + self.loop.remove_reader(self.pidfd) + self.fut.set_result(result) + + +def async_waitpidfd( + pidfd: int, flags: int +) -> asyncio.Future[os.waitid_result | None]: + """Asynchronously wait for a process represented as a pidfd. This is an + async variant of waitid(P_PIDFD, pidfd, flags). + """ + return _AsyncPidfdWaiter(pidfd, flags).fut -- cgit v1.2.3