artifactize-foundation 0.27.0

Native file, path and executable primitives for Artifactize.
Documentation
//! On Linux, keep orphaned group descendants waitable by their supervisor.

use super::{Errno, Pid, WaitId, WaitIdOptions, native_pid, process_ids};
use crate::platform::process::ProcessId;
use rustix::process::{PidfdFlags, pidfd_open, set_child_subreaper};
use std::{io, os::fd::AsFd};

pub(super) fn enable() -> io::Result<()> {
    // Subreaping is a per-process kernel attribute, not a per-thread setting.
    // Set it before spawn, so even an immediate double-fork is adopted here.
    set_child_subreaper(Some(rustix::process::getpid()))?;
    Ok(())
}

/// Only reap adopted members of this group. A blanket wait(-1) would steal exit
/// statuses from unrelated native child handles in this process. The caller keeps
/// the leader unreaped and has already observed that all members stopped.
pub(super) fn reap_adopted(
    leader: ProcessId,
    membership: impl Fn(Pid) -> io::Result<Option<Pid>>,
) -> io::Result<()> {
    let leader = native_pid(leader.get())?;
    for pid in process_ids()?.into_iter().filter_map(Pid::from_raw) {
        if pid == leader || membership(pid)? != Some(leader) {
            continue;
        }
        let handle = match pidfd_open(pid, PidfdFlags::empty()) {
            Ok(handle) => handle,
            Err(Errno::SRCH) => continue,
            Err(error) => return Err(error.into()),
        };
        if membership(pid)? != Some(leader) {
            continue;
        }
        loop {
            // ECHILD is possible if a member is still owned by a different
            // parent. Its death was already checked; we must not wait on it.
            match rustix::process::waitid(
                WaitId::PidFd(handle.as_fd()),
                WaitIdOptions::EXITED | WaitIdOptions::NOHANG,
            ) {
                Ok(_) | Err(Errno::CHILD | Errno::SRCH) => break,
                Err(Errno::INTR) => continue,
                Err(error) => return Err(error.into()),
            }
        }
    }
    Ok(())
}