use std::time::Duration;
#[cfg(unix)]
pub fn configure_command_for_process_group(command: &mut tokio::process::Command) {
unsafe {
command.pre_exec(|| {
if libc::setpgid(0, 0) != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
}
#[cfg(not(unix))]
pub fn configure_command_for_process_group(command: &mut tokio::process::Command) {
let _ = command;
}
#[cfg(unix)]
fn send_signal_to_process_group_or_pid(pid: u32, signal: i32) -> bool {
if pid == 0 {
return false;
}
let raw_pid = pid as libc::pid_t;
let group_ok = unsafe { libc::kill(-raw_pid, signal) == 0 };
if group_ok {
return true;
}
unsafe { libc::kill(raw_pid, signal) == 0 }
}
#[cfg(unix)]
pub fn send_sigterm(pid: u32) -> bool {
send_signal_to_process_group_or_pid(pid, libc::SIGTERM)
}
#[cfg(unix)]
pub fn send_sigkill(pid: u32) -> bool {
send_signal_to_process_group_or_pid(pid, libc::SIGKILL)
}
#[cfg(not(unix))]
pub fn send_sigterm(pid: u32) -> bool {
taskkill(pid, false)
}
#[cfg(not(unix))]
pub fn send_sigkill(pid: u32) -> bool {
taskkill(pid, true)
}
#[cfg(not(unix))]
fn taskkill(pid: u32, force: bool) -> bool {
if pid == 0 {
return false;
}
let mut command = std::process::Command::new("taskkill");
command.args(["/PID", &pid.to_string(), "/T"]);
if force {
command.arg("/F");
}
command
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|status| status.success())
}
pub async fn terminate_process_tree(pid: u32, child: &mut tokio::process::Child, grace: Duration) {
#[cfg(unix)]
{
if !send_sigterm(pid) {
let _ = child.start_kill();
}
let exited = tokio::time::timeout(grace, child.wait()).await;
if exited.is_err() {
let _ = send_sigkill(pid);
let _ = tokio::time::timeout(Duration::from_secs(1), child.wait()).await;
}
}
#[cfg(not(unix))]
{
if !send_sigterm(pid) {
let _ = child.start_kill();
}
if tokio::time::timeout(grace, child.wait()).await.is_err() {
if !send_sigkill(pid) {
let _ = child.start_kill();
}
let _ = tokio::time::timeout(Duration::from_secs(1), child.wait()).await;
}
}
}
#[cfg(any(windows, test))]
#[allow(dead_code)] mod win32_job {
#[repr(C)]
#[derive(Debug, Default, Clone, Copy)]
pub(super) struct JobObjectBasicLimitInformation {
pub per_process_user_time_limit: i64, pub per_job_user_time_limit: i64, pub limit_flags: u32, pub minimum_working_set_size: usize, pub maximum_working_set_size: usize, pub active_process_limit: u32, pub affinity: usize, pub priority_class: u32, pub scheduling_class: u32, }
#[repr(C)]
#[derive(Debug, Default, Clone, Copy)]
pub(super) struct IoCounters {
pub read_operation_count: u64,
pub write_operation_count: u64,
pub other_operation_count: u64,
pub read_transfer_count: u64,
pub write_transfer_count: u64,
pub other_transfer_count: u64,
}
#[repr(C)]
#[derive(Debug, Default, Clone, Copy)]
pub(super) struct JobObjectExtendedLimitInformation {
pub basic_limit_information: JobObjectBasicLimitInformation,
pub io_info: IoCounters,
pub process_memory_limit: usize, pub job_memory_limit: usize, pub peak_process_memory_used: usize, pub peak_job_memory_used: usize, }
pub(super) const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS: i32 = 9;
pub(super) const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: u32 = 0x2000;
#[cfg(windows)]
#[link(name = "kernel32")]
unsafe extern "system" {
pub(super) fn CreateJobObjectW(
job_attributes: *const std::ffi::c_void,
name: *const u16,
) -> *mut std::ffi::c_void;
pub(super) fn SetInformationJobObject(
job: *mut std::ffi::c_void,
information_class: i32,
information: *const std::ffi::c_void,
information_length: u32,
) -> i32;
pub(super) fn AssignProcessToJobObject(
job: *mut std::ffi::c_void,
process: *mut std::ffi::c_void,
) -> i32;
pub(super) fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;
}
}
#[cfg(windows)]
pub struct JobObject {
handle: std::ptr::NonNull<std::ffi::c_void>,
}
#[cfg(windows)]
unsafe impl Send for JobObject {}
#[cfg(windows)]
unsafe impl Sync for JobObject {}
#[cfg(windows)]
impl JobObject {
pub fn kill_on_close() -> std::io::Result<Self> {
use win32_job::*;
let raw = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
let handle = std::ptr::NonNull::new(raw).ok_or_else(std::io::Error::last_os_error)?;
let job = Self { handle };
let mut info = JobObjectExtendedLimitInformation::default();
info.basic_limit_information.limit_flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
let ok = unsafe {
SetInformationJobObject(
job.handle.as_ptr(),
JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS,
(&raw const info).cast(),
std::mem::size_of::<JobObjectExtendedLimitInformation>() as u32,
)
};
if ok == 0 {
return Err(std::io::Error::last_os_error());
}
Ok(job)
}
pub fn assign(&self, child: &tokio::process::Child) -> std::io::Result<()> {
let Some(process) = child.raw_handle() else {
return Err(std::io::Error::other("child already reaped"));
};
let ok = unsafe { win32_job::AssignProcessToJobObject(self.handle.as_ptr(), process) };
if ok == 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
}
#[cfg(windows)]
impl Drop for JobObject {
fn drop(&mut self) {
unsafe {
win32_job::CloseHandle(self.handle.as_ptr());
}
}
}
#[cfg(windows)]
fn daemon_job() -> Option<&'static JobObject> {
static JOB: std::sync::OnceLock<Option<JobObject>> = std::sync::OnceLock::new();
JOB.get_or_init(|| match JobObject::kill_on_close() {
Ok(job) => Some(job),
Err(error) => {
tracing::warn!(%error, "could not create the kill-on-close job object; spawned processes may outlive the daemon");
None
}
})
.as_ref()
}
pub fn bind_child_to_daemon_lifetime(child: &tokio::process::Child) {
#[cfg(windows)]
{
let Some(job) = daemon_job() else {
return;
};
if let Err(error) = job.assign(child) {
tracing::debug!(%error, pid = child.id(), "could not add child to the kill-on-close job");
}
}
#[cfg(not(windows))]
let _ = child;
}
#[cfg(test)]
mod tests {
use super::win32_job::*;
use std::mem::{align_of, offset_of, size_of};
#[test]
fn job_limit_structs_match_winnt_layout() {
let word = size_of::<usize>();
assert_eq!(size_of::<IoCounters>(), 48);
assert_eq!(offset_of!(JobObjectBasicLimitInformation, limit_flags), 16);
assert_eq!(
offset_of!(JobObjectExtendedLimitInformation, io_info),
size_of::<JobObjectBasicLimitInformation>()
);
assert_eq!(
offset_of!(JobObjectExtendedLimitInformation, process_memory_limit),
size_of::<JobObjectBasicLimitInformation>() + 48
);
assert_eq!(
size_of::<JobObjectExtendedLimitInformation>(),
size_of::<JobObjectBasicLimitInformation>() + 48 + 4 * word
);
assert_eq!(align_of::<JobObjectExtendedLimitInformation>(), 8);
assert_eq!(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, 0x2000);
assert_eq!(JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS, 9);
}
#[cfg(target_pointer_width = "64")]
#[test]
fn job_limit_structs_match_winnt_layout_64_bit() {
type Basic = JobObjectBasicLimitInformation;
assert_eq!(offset_of!(Basic, per_process_user_time_limit), 0);
assert_eq!(offset_of!(Basic, per_job_user_time_limit), 8);
assert_eq!(offset_of!(Basic, limit_flags), 16);
assert_eq!(offset_of!(Basic, minimum_working_set_size), 24);
assert_eq!(offset_of!(Basic, maximum_working_set_size), 32);
assert_eq!(offset_of!(Basic, active_process_limit), 40);
assert_eq!(offset_of!(Basic, affinity), 48);
assert_eq!(offset_of!(Basic, priority_class), 56);
assert_eq!(offset_of!(Basic, scheduling_class), 60);
assert_eq!(size_of::<Basic>(), 64);
type Extended = JobObjectExtendedLimitInformation;
assert_eq!(offset_of!(Extended, io_info), 64);
assert_eq!(offset_of!(Extended, process_memory_limit), 112);
assert_eq!(offset_of!(Extended, job_memory_limit), 120);
assert_eq!(offset_of!(Extended, peak_process_memory_used), 128);
assert_eq!(offset_of!(Extended, peak_job_memory_used), 136);
assert_eq!(size_of::<Extended>(), 144);
}
#[cfg(windows)]
#[tokio::test]
async fn closing_the_job_ends_its_process() {
let job = super::JobObject::kill_on_close().expect("create job");
let mut child = tokio::process::Command::new("cmd")
.args(["/C", "ping -n 30 127.0.0.1 >NUL"])
.stdout(std::process::Stdio::null())
.kill_on_drop(true)
.spawn()
.expect("spawn");
job.assign(&child).expect("assign");
drop(job);
let status = tokio::time::timeout(std::time::Duration::from_secs(10), child.wait())
.await
.expect("child ended with the job")
.expect("wait");
assert!(!status.success());
}
}