darwin_libproc/
list_pids.rs

1use std::io;
2use std::mem;
3use std::ptr;
4
5fn list_pids(r#type: u32, typeinfo: u32) -> io::Result<Vec<libc::pid_t>> {
6    let size = unsafe {
7        darwin_libproc_sys::proc_listpids(r#type, typeinfo, ptr::null_mut(), 0)
8    };
9    if size <= 0 {
10        return Err(io::Error::last_os_error());
11    }
12
13    let capacity = size as usize / mem::size_of::<libc::pid_t>();
14    let mut buffer: Vec<libc::pid_t> = Vec::with_capacity(capacity);
15
16    let result = unsafe {
17        darwin_libproc_sys::proc_listpids(
18            r#type,
19            typeinfo,
20            buffer.as_mut_ptr() as *mut libc::c_void,
21            size,
22        )
23    };
24    if result <= 0 {
25        return Err(io::Error::last_os_error());
26    }
27
28    let pids_count = result as usize / mem::size_of::<libc::pid_t>();
29    unsafe {
30        buffer.set_len(pids_count);
31    }
32
33    Ok(buffer)
34}
35
36/// Fetch pids for all processes running in system.
37pub fn all_pids() -> io::Result<Vec<libc::pid_t>> {
38    list_pids(darwin_libproc_sys::PROC_ALL_PIDS, 0)
39}
40
41/// Fetch pids for processes running in system in a given group.
42pub fn pgrp_only_pids(pgrpid: libc::pid_t) -> io::Result<Vec<libc::pid_t>> {
43    list_pids(darwin_libproc_sys::PROC_PGRP_ONLY, pgrpid as u32)
44}
45
46/// Fetch pids for processes running in system attached to a given TTY.
47pub fn tty_only_pids(tty: libc::c_int) -> io::Result<Vec<libc::pid_t>> {
48    list_pids(darwin_libproc_sys::PROC_TTY_ONLY, tty as u32)
49}
50
51/// Fetch pids for processes running in system with the given UID.
52pub fn uid_only_pids(uid: libc::uid_t) -> io::Result<Vec<libc::pid_t>> {
53    list_pids(darwin_libproc_sys::PROC_UID_ONLY, uid)
54}
55
56/// Fetch pids for processes running in system with the given RUID.
57pub fn ruid_only_pids(ruid: libc::uid_t) -> io::Result<Vec<libc::pid_t>> {
58    list_pids(darwin_libproc_sys::PROC_RUID_ONLY, ruid)
59}
60
61/// Fetch pids for processes running in system with the given PPID.
62pub fn ppid_only_pids(ppid: libc::pid_t) -> io::Result<Vec<libc::pid_t>> {
63    list_pids(darwin_libproc_sys::PROC_PPID_ONLY, ppid as u32)
64}