use libc::{ SA_RESTART, SA_SIGINFO, SIGCHLD, WNOHANG, c_int, sigaction, siginfo_t, sigset_t, waitpid, }; use std::os::raw::c_void; // extern "C" because: // https://doc.rust-lang.org/reference/items/external-blocks.html?spm=a2ty_o01.29997173.0.0.63e251718NCvPc#abi // Doc comments needed... extern "C" fn sigchld_handler(_signal: c_int, _info: *mut siginfo_t, _context: *mut c_void) { let saved_errno = unsafe { *libc::__errno_location() }; loop { let mut status: c_int = 0; let pid = unsafe { waitpid(-1, &mut status as *mut c_int, WNOHANG) }; match pid { 0 => break, -1 => { let errno = unsafe { *libc::__errno_location() }; if errno == libc::ECHILD { break; } } _ => { /* If it doesnt work, ill add the logging here */ } } } unsafe { *libc::__errno_location() = saved_errno }; } pub fn setup_sigchld_handler() -> Result<(), Box> { unsafe { let mut sigact: sigaction = std::mem::zeroed(); sigact.sa_sigaction = sigchld_handler as *const () as usize; sigact.sa_flags = SA_RESTART | SA_SIGINFO; libc::sigemptyset(&mut sigact.sa_mask as *mut sigset_t); libc::sigaddset(&mut sigact.sa_mask as *mut sigset_t, SIGCHLD); if libc::sigaction(SIGCHLD, &sigact, std::ptr::null_mut()) == -1 { return Err("Failed to set SIGCHLD handler".into()); } } Ok(()) }