Skip to content

Instantly share code, notes, and snippets.

@nguyen-phillip
Created November 15, 2019 01:33
Show Gist options
  • Save nguyen-phillip/e19d993abb9c4f7402eeeafd9a8238d8 to your computer and use it in GitHub Desktop.
Save nguyen-phillip/e19d993abb9c4f7402eeeafd9a8238d8 to your computer and use it in GitHub Desktop.
Using libproc from Python with ctypes
import ctypes
libproc = ctypes.cdll.LoadLibrary('/usr/lib/libproc.dylib')
# int proc_listallpids(void * buffer, int buffersize)
libproc.proc_listallpids.res_type = ctypes.c_int
libproc.proc_listallpids.arg_types = [ctypes.c_void_p, ctypes.c_int]
# int proc_pidpath(int pid, void * buffer, uint32_t buffersize)
libproc.proc_pidpath.res_type = ctypes.c_int
libproc.proc_pidpath.arg_types = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int]
# Defined in sys/proc_info.h
PROC_PIDPATHINFO_MAXSIZE = 4096
def get_all_pids():
n = libproc.proc_listallpids(None, 0)
pids = (ctypes.c_int * n)()
count = libproc.proc_listallpids(pids, ctypes.sizeof(pids))
return [pids[i] for i in xrange(count)]
def get_pid_path(pid):
buf = ctypes.create_string_buffer(PROC_PIDPATHINFO_MAXSIZE)
if libproc.proc_pidpath(pid, buf, ctypes.sizeof(buf)) > 0:
return buf.value
return None
if __name__ == '__main__':
for pid in get_all_pids():
print pid, get_pid_path(pid) or ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment