Skip to content

Instantly share code, notes, and snippets.

@daskol
Last active June 17, 2021 15:47
Show Gist options
  • Save daskol/703b0a0ee51a8100445230248b5357d4 to your computer and use it in GitHub Desktop.
Save daskol/703b0a0ee51a8100445230248b5357d4 to your computer and use it in GitHub Desktop.
Event multiplexing on process identifiers (PIDs)
#!/usr/bin/env python3
"""This script demonstrates event multiplexing on process identifiers (PIDs).
More specifically, we issue file descriptor (FD) from PID and. Then we wait
events on the descriptor. Note that polling such events is feasible because of
obtaining FD from PID with pidfd_open() system call. This feature was
introduced in 5.3 (Sep 2019). A usage example is below.
$ ./wait4pid.py 1337 &
$ kill -9 1337
process with pid 1337 exited
"""
from ctypes import CDLL
from select import POLLIN, poll
from sys import argv
def pidfd_open(pid, flags=None):
"""Function pidfd_open wraps making system call since there is no binding
in libc.
"""
return CDLL(None).syscall(434, pid, flags or 0)
def watch(pid, timeout=None):
fd = pidfd_open(pid)
poller = poll()
poller.register(fd, POLLIN)
for fd, ev in poller.poll(timeout):
print('process with pid', pid, 'exited')
poller.unregister(fd)
def main():
try:
pid = int(argv[1])
timeout = float(argv[2]) if len(argv) >= 3 else None
except Exception:
print('usage:', argv[0], '<pid:int> [timeout:float]')
return
watch(pid, timeout)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment