alpha2_os/worker.rs
1//! A worker child process on its standard streams, and its parent's handle on its process tree.
2
3use std::fs::File;
4use std::io;
5use std::process::{Child, Command};
6
7/// Takes standard input for a protocol stream.
8///
9/// Returns a reader on the stream standard input was, which children do not inherit, and points
10/// standard input at the null device, so a library that reads standard input reads nothing. On
11/// Windows the C runtime's descriptor 0 follows too.
12///
13/// # Errors
14/// When standard input is closed or cannot be duplicated.
15pub fn claim_stdin() -> io::Result<File> {
16 #[cfg(unix)]
17 {
18 crate::platform::claim_stdin()
19 }
20 #[cfg(windows)]
21 {
22 crate::platform::claim_stdin()
23 }
24 #[cfg(not(any(unix, windows)))]
25 {
26 Err(io::Error::from(io::ErrorKind::Unsupported))
27 }
28}
29
30/// Closes every descriptor above standard error except those of `keep` (Unix only). Call it at
31/// the start of the process, before anything opens a descriptor it keeps.
32pub fn close_descriptors_except(keep: &[&File]) {
33 #[cfg(unix)]
34 {
35 use std::os::fd::AsRawFd;
36 let keep = keep.iter().map(|file| file.as_raw_fd()).collect::<Vec<_>>();
37 crate::platform::close_descriptors_except(&keep);
38 }
39 #[cfg(not(unix))]
40 let _ = keep;
41}
42
43/// Turns off core files (Unix) and crash dialogs (Windows) for this process.
44pub fn disable_crash_dumps() {
45 #[cfg(unix)]
46 {
47 let none = libc::rlimit {
48 rlim_cur: 0,
49 rlim_max: 0,
50 };
51 // SAFETY: `none` is a valid `rlimit` read by the call; lowering a limit needs no rights.
52 let _ = unsafe { libc::setrlimit(libc::RLIMIT_CORE, &raw const none) };
53 }
54 #[cfg(windows)]
55 {
56 use windows_sys::Win32::System::Diagnostics::Debug::{
57 SEM_FAILCRITICALERRORS, SEM_NOGPFAULTERRORBOX, SetErrorMode,
58 };
59 // SAFETY: `SetErrorMode` takes flags only.
60 unsafe { SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX) };
61 }
62}
63
64/// Makes this process the out-of-memory killer's first choice (Linux). Does nothing elsewhere.
65pub fn prefer_out_of_memory_kill() {
66 #[cfg(any(target_os = "linux", target_os = "android"))]
67 {
68 let _ = std::fs::write("/proc/self/oom_score_adj", "1000");
69 }
70}
71
72/// Starts the child `command` spawns in its own process group (Unix) or without a console
73/// (Windows); on Windows also put the child in a [`crate::KillOnCloseJob`].
74pub fn own_process_tree(command: &mut Command) {
75 #[cfg(unix)]
76 {
77 use std::os::unix::process::CommandExt;
78 command.process_group(0);
79 }
80 #[cfg(windows)]
81 {
82 use std::os::windows::process::CommandExt;
83 use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
84 command.creation_flags(CREATE_NO_WINDOW);
85 }
86 #[cfg(not(any(unix, windows)))]
87 let _ = command;
88}
89
90/// Whether `child` has ended, without reaping it: until it is waited for, its id names it and the
91/// process group it leads, so [`kill_process_tree`] still reaches what it started.
92///
93/// # Errors
94/// When the operating system cannot tell.
95pub fn child_exited(child: &mut Child) -> io::Result<bool> {
96 #[cfg(unix)]
97 {
98 let pid = libc::id_t::from(child.id());
99 // SAFETY: an all-zero `siginfo_t` is a valid value for the call to fill.
100 let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
101 // SAFETY: `info` outlives the call; `WNOWAIT` leaves the child waitable.
102 let waited = unsafe {
103 libc::waitid(
104 libc::P_PID,
105 pid,
106 &raw mut info,
107 libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
108 )
109 };
110 if waited != 0 {
111 return Err(io::Error::last_os_error());
112 }
113 // SAFETY: `waitid` filled `info`; a zero pid means the child has not ended.
114 Ok(unsafe { info.si_pid() } != 0)
115 }
116 #[cfg(not(unix))]
117 {
118 child.try_wait().map(|status| status.is_some())
119 }
120}
121
122/// Kills `child` and, on Unix, every process of the group [`own_process_tree`] gave it; call it
123/// before the child is reaped, while its id still names the group. On Windows dropping the
124/// child's job ends the processes the child started.
125///
126/// # Errors
127/// When the child cannot be killed.
128pub fn kill_process_tree(child: &mut Child) -> io::Result<()> {
129 #[cfg(unix)]
130 if let Ok(group) = libc::pid_t::try_from(child.id()) {
131 // SAFETY: `kill` takes plain values; the group of a reaped child may be gone (ESRCH).
132 let _ = unsafe { libc::kill(-group, libc::SIGKILL) };
133 }
134 child.kill()
135}