use std::fs::File;
use std::io;
use std::process::{Child, Command};
pub fn claim_stdin() -> io::Result<File> {
#[cfg(unix)]
{
crate::platform::claim_stdin()
}
#[cfg(windows)]
{
crate::platform::claim_stdin()
}
#[cfg(not(any(unix, windows)))]
{
Err(io::Error::from(io::ErrorKind::Unsupported))
}
}
pub fn close_descriptors_except(keep: &[&File]) {
#[cfg(unix)]
{
use std::os::fd::AsRawFd;
let keep = keep.iter().map(|file| file.as_raw_fd()).collect::<Vec<_>>();
crate::platform::close_descriptors_except(&keep);
}
#[cfg(not(unix))]
let _ = keep;
}
pub fn disable_crash_dumps() {
#[cfg(unix)]
{
let none = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
let _ = unsafe { libc::setrlimit(libc::RLIMIT_CORE, &raw const none) };
}
#[cfg(windows)]
{
use windows_sys::Win32::System::Diagnostics::Debug::{
SEM_FAILCRITICALERRORS, SEM_NOGPFAULTERRORBOX, SetErrorMode,
};
unsafe { SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX) };
}
}
pub fn prefer_out_of_memory_kill() {
#[cfg(any(target_os = "linux", target_os = "android"))]
{
let _ = std::fs::write("/proc/self/oom_score_adj", "1000");
}
}
pub fn own_process_tree(command: &mut Command) {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
command.creation_flags(CREATE_NO_WINDOW);
}
#[cfg(not(any(unix, windows)))]
let _ = command;
}
pub fn child_exited(child: &mut Child) -> io::Result<bool> {
#[cfg(unix)]
{
let pid = libc::id_t::from(child.id());
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let waited = unsafe {
libc::waitid(
libc::P_PID,
pid,
&raw mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if waited != 0 {
return Err(io::Error::last_os_error());
}
Ok(unsafe { info.si_pid() } != 0)
}
#[cfg(not(unix))]
{
child.try_wait().map(|status| status.is_some())
}
}
pub fn kill_process_tree(child: &mut Child) -> io::Result<()> {
#[cfg(unix)]
if let Ok(group) = libc::pid_t::try_from(child.id()) {
let _ = unsafe { libc::kill(-group, libc::SIGKILL) };
}
child.kill()
}