1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
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<dyn std::error::Error>> {
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(())
}
|