oxedyne/fe2o3/fe2o3_sys/src/signal.rs
10.7 KiB, 18 runs
created by r1870400018:66883, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! Signals to the caller's own process group, to a group it started, to one process, and to a |
| 2 | //! process and all it started. |
| 3 | //! |
| 4 | //! A program that runs a child it must end when asked to stop, an editor under `ore edit`, has two |
| 5 | //! ways to reach it. The child shares the caller's process group where the caller was started as |
| 6 | //! a job by an interactive shell, and a signal to the group then reaches the child and whatever it |
| 7 | //! started in turn. Where the caller was not, as under a script or a test harness, the group is its |
| 8 | //! parent's, and signalling it would reach that parent's other processes; [`to_own_group`] declines |
| 9 | //! to, and [`to_tree`] reaches the child and everything it started, which is what a child run through |
| 10 | //! `sh -c` needs, since the shell is not the program. |
| 11 | //! |
| 12 | //! The shell that stands between the caller and the program ends at once when it is signalled, and |
| 13 | //! the caller waiting on it alone would think the program over while it ran on. [`tree_of`] reads the |
| 14 | //! whole tree before anything is signalled, [`to_members`] signals the processes farthest from the |
| 15 | //! child first, so that none is left without its parent's death to find out about, and |
| 16 | //! [`still_running`] answers which of them are yet to end. |
| 17 | //! |
| 18 | //! The system calls come from `nix`, which owns the `unsafe` this crate forbids. |
| 19 | |
| 20 | use oxedyne_fe2o3_core::prelude::*; |
| 21 | |
| 22 | use nix::sys::signal::{ |
| 23 | kill, |
| 24 | killpg, |
| 25 | Signal as Sig, |
| 26 | }; |
| 27 | use nix::unistd::{ |
| 28 | getpgrp, |
| 29 | getpid, |
| 30 | Pid, |
| 31 | }; |
| 32 | |
| 33 | /// A signal that asks a process to end, or with `Kill` ends it where it stands; `Stop` |
| 34 | /// holds it where it stands and `Continue` lets it go on. |
| 35 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 36 | pub enum Signal { |
| 37 | Hangup, |
| 38 | Interrupt, |
| 39 | Terminate, |
| 40 | Kill, |
| 41 | Stop, |
| 42 | Continue, |
| 43 | } |
| 44 | |
| 45 | impl Signal { |
| 46 | pub(crate) fn nix(&self) -> Sig { |
| 47 | match self { |
| 48 | Self::Hangup => Sig::SIGHUP, |
| 49 | Self::Interrupt => Sig::SIGINT, |
| 50 | Self::Terminate => Sig::SIGTERM, |
| 51 | Self::Kill => Sig::SIGKILL, |
| 52 | Self::Stop => Sig::SIGSTOP, |
| 53 | Self::Continue => Sig::SIGCONT, |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// Does the caller lead its own process group? |
| 59 | pub fn leads_its_group() -> bool { |
| 60 | getpgrp() == getpid() |
| 61 | } |
| 62 | |
| 63 | /// Sends `sig` to every process in the caller's own process group, the caller included, and |
| 64 | /// answers whether it did. |
| 65 | /// |
| 66 | /// It declines, answering false and sending nothing, where the caller does not lead the group: |
| 67 | /// the group is then shared with the process that started the caller, and with its other children. |
| 68 | pub fn to_own_group(sig: Signal) -> Outcome<bool> { |
| 69 | if !leads_its_group() { |
| 70 | return Ok(false); |
| 71 | } |
| 72 | match killpg(getpgrp(), sig.nix()) { |
| 73 | Ok(()) => Ok(true), |
| 74 | Err(e) => Err(err!( |
| 75 | "Cannot send {:?} to the caller's own process group: {}.", sig, e; |
| 76 | IO, System)), |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | /// Sends `sig` to every process in the process group `pgid`, a group the caller started a child |
| 81 | /// to lead, as with `Command::process_group(0)`, whose group number is then the child's pid. |
| 82 | /// |
| 83 | /// It refuses group 0, which the kernel reads as the caller's own group, group 1, and the caller's |
| 84 | /// own group by its number, since a caller that means its own group asks [`to_own_group`]. |
| 85 | pub fn to_group(pgid: u32, sig: Signal) -> Outcome<()> { |
| 86 | if pgid <= 1 { |
| 87 | return Err(err!( |
| 88 | "The process group {} is not one a signal can be sent to: 0 is the caller's own \ |
| 89 | group and 1 is init's.", pgid; |
| 90 | Invalid, Input, Range)); |
| 91 | } |
| 92 | let group = match i32::try_from(pgid) { |
| 93 | Ok(g) => Pid::from_raw(g), |
| 94 | Err(_) => return Err(err!( |
| 95 | "The process group {} is not one a signal can be sent to.", pgid; |
| 96 | Invalid, Input, Range)), |
| 97 | }; |
| 98 | if group == getpgrp() { |
| 99 | return Err(err!( |
| 100 | "The process group {} is the caller's own; to_own_group signals it.", pgid; |
| 101 | Invalid, Input)); |
| 102 | } |
| 103 | match killpg(group, sig.nix()) { |
| 104 | Ok(()) => Ok(()), |
| 105 | Err(e) => Err(err!( |
| 106 | "Cannot send {:?} to process group {}: {}.", sig, pgid, e; |
| 107 | IO, System)), |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | /// Sends `sig` to the one process `pid`. |
| 112 | pub fn to_process(pid: u32, sig: Signal) -> Outcome<()> { |
| 113 | let pid = match i32::try_from(pid) { |
| 114 | Ok(p) => Pid::from_raw(p), |
| 115 | Err(_) => return Err(err!( |
| 116 | "The process number {} is not one a signal can be sent to.", pid; |
| 117 | Invalid, Input, Range)), |
| 118 | }; |
| 119 | match kill(pid, sig.nix()) { |
| 120 | Ok(()) => Ok(()), |
| 121 | Err(e) => Err(err!( |
| 122 | "Cannot send {:?} to process {}: {}.", sig, pid, e; |
| 123 | IO, System)), |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | /// A process, told from a later one that is given its number. |
| 128 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 129 | pub struct Proc { |
| 130 | pub pid: u32, |
| 131 | start: u64, // the tick it began on, which a process that takes the number later does not share |
| 132 | } |
| 133 | |
| 134 | impl Proc { |
| 135 | /// The process now running as `pid`, where there is one that has not ended. |
| 136 | pub fn of(pid: u32) -> Option<Self> { |
| 137 | match Stat::of(pid) { |
| 138 | Some(st) if st.state != 'Z' => Some(Self { pid, start: st.start }), |
| 139 | _ => None, |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | /// Is it still running? One that has ended and awaits only its parent's wait is not. |
| 144 | pub fn running(&self) -> bool { |
| 145 | match Stat::of(self.pid) { |
| 146 | Some(st) => st.start == self.start && st.state != 'Z', |
| 147 | None => false, |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | // What /proc/<pid>/stat says of a process, the fields this module asks. |
| 153 | struct Stat { |
| 154 | state: char, |
| 155 | parent: u32, |
| 156 | start: u64, |
| 157 | } |
| 158 | |
| 159 | impl Stat { |
| 160 | fn of(pid: u32) -> Option<Self> { |
| 161 | let text = std::fs::read_to_string(format!("/proc/{}/stat", pid)).ok()?; |
| 162 | Self::parse(&text) |
| 163 | } |
| 164 | |
| 165 | fn parse(text: &str) -> Option<Self> { |
| 166 | // The command name is in parentheses and may hold spaces and brackets, so the fields are |
| 167 | // counted from the last one: the state is the first after it, the parent the second, and |
| 168 | // the start time the twentieth. |
| 169 | let after = &text[text.rfind(')')? + 1..]; |
| 170 | let mut fields = after.split_whitespace(); |
| 171 | let state = fields.next()?.chars().next()?; |
| 172 | let parent = fields.next()?.parse().ok()?; |
| 173 | let start = fields.nth(17)?.parse().ok()?; |
| 174 | Some(Self { state, parent, start }) |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | /// `pid` and every process it started, however deep, as they are now: those nearest `pid` come |
| 179 | /// first, so that a process is always after the one that started it. |
| 180 | /// |
| 181 | /// A process that has ended and awaits only its parent's wait is not in it, and nor is anything it |
| 182 | /// started that was passed to another parent when it ended. |
| 183 | pub fn tree_of(pid: u32) -> Outcome<Vec<Proc>> { |
| 184 | let dir = match std::fs::read_dir("/proc") { |
| 185 | Ok(d) => d, |
| 186 | Err(e) => return Err(err!(e, |
| 187 | "Cannot read /proc to find the processes process {} started.", pid; |
| 188 | IO, File, Read)), |
| 189 | }; |
| 190 | let mut all: Vec<(u32, Stat)> = Vec::new(); |
| 191 | for entry in dir.flatten() { |
| 192 | let me: u32 = match entry.file_name().to_str().and_then(|n| n.parse().ok()) { |
| 193 | Some(n) => n, |
| 194 | None => continue, |
| 195 | }; |
| 196 | match Stat::of(me) { |
| 197 | Some(st) if st.state != 'Z' => all.push((me, st)), |
| 198 | _ => continue, |
| 199 | } |
| 200 | } |
| 201 | let mut found: Vec<Proc> = Vec::new(); |
| 202 | for (me, st) in &all { |
| 203 | if *me == pid { |
| 204 | found.push(Proc { pid: *me, start: st.start }); |
| 205 | } |
| 206 | } |
| 207 | let mut at = 0; |
| 208 | while at < found.len() { |
| 209 | let of = found[at].pid; |
| 210 | at += 1; |
| 211 | for (me, st) in &all { |
| 212 | if st.parent == of && !found.iter().any(|p| p.pid == *me) { |
| 213 | found.push(Proc { pid: *me, start: st.start }); |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | Ok(found) |
| 218 | } |
| 219 | |
| 220 | /// Sends `sig` to each of `tree`, the farthest from the first first, and answers the processes it |
| 221 | /// reached in the order it reached them. |
| 222 | /// |
| 223 | /// A process that has ended since the tree was read, or whose number another process now holds, is |
| 224 | /// passed over. |
| 225 | pub fn to_members(tree: &[Proc], sig: Signal) -> Vec<u32> { |
| 226 | let mut sent = Vec::new(); |
| 227 | for one in tree.iter().rev() { |
| 228 | if Proc::of(one.pid) != Some(*one) { |
| 229 | continue; |
| 230 | } |
| 231 | if to_process(one.pid, sig).is_ok() { |
| 232 | sent.push(one.pid); |
| 233 | } |
| 234 | } |
| 235 | sent |
| 236 | } |
| 237 | |
| 238 | /// Sends `sig` to `pid` and to every process it started, however deep, the farthest first, and |
| 239 | /// answers the processes it reached in the order it reached them. |
| 240 | pub fn to_tree(pid: u32, sig: Signal) -> Outcome<Vec<u32>> { |
| 241 | let tree = res!(tree_of(pid)); |
| 242 | Ok(to_members(&tree, sig)) |
| 243 | } |
| 244 | |
| 245 | /// Which of `tree` are yet to end. |
| 246 | pub fn still_running(tree: &[Proc]) -> Vec<Proc> { |
| 247 | tree.iter().filter(|p| p.running()).copied().collect() |
| 248 | } |
| 249 | |
| 250 | #[cfg(test)] |
| 251 | mod tests { |
| 252 | use super::*; |
| 253 | |
| 254 | use std::process::Command; |
| 255 | |
| 256 | #[test] |
| 257 | fn a_name_with_brackets_and_spaces_does_not_move_the_fields() { |
| 258 | let line = "4242 (a b) (c) d) S 17 4242 4242 0 -1 4194560 100 0 0 0 1 2 0 0 20 0 1 0 987654 1000 20 \ |
| 259 | 18446744073709551615 0 0 0 0 0 0 0 0 0 0 0 0 17 0 0 0 0 0 0"; |
| 260 | let st = Stat::parse(line); |
| 261 | assert!(matches!(st, Some(Stat { state: 'S', parent: 17, start: 987_654 }))); |
| 262 | assert!(Stat::parse("no brackets here").is_none()); |
| 263 | assert!(Stat::parse("4242 (cut) S 17").is_none()); |
| 264 | } |
| 265 | |
| 266 | // The kernel's own order of events: init began before the process this test has just started, and |
| 267 | // the new one began a moment ago by the clock `/proc/uptime` keeps. |
| 268 | #[test] |
| 269 | fn the_start_it_reads_agrees_with_the_order_the_kernel_started_the_processes_in() { |
| 270 | let mut child = match Command::new("sleep").arg("5").spawn() { |
| 271 | Ok(c) => c, |
| 272 | Err(e) => panic!("cannot start a sleep: {}", e), |
| 273 | }; |
| 274 | let kid = Stat::of(child.id()); |
| 275 | let init = Stat::of(1); |
| 276 | let up: f64 = std::fs::read_to_string("/proc/uptime").ok() |
| 277 | .and_then(|t| t.split_whitespace().next().and_then(|f| f.parse().ok())) |
| 278 | .unwrap_or(0.0); |
| 279 | let ticks: f64 = Command::new("getconf").arg("CLK_TCK").output().ok() |
| 280 | .and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok()) |
| 281 | .unwrap_or(100.0); |
| 282 | let _ = child.kill(); |
| 283 | let _ = child.wait(); |
| 284 | match (kid, init) { |
| 285 | (Some(kid), Some(init)) => { |
| 286 | assert!(init.start <= kid.start, "init {} began after the sleep {}", init.start, kid.start); |
| 287 | let age = up - kid.start as f64 / ticks; |
| 288 | assert!((0.0..20.0).contains(&age), "the sleep is {} s old by the kernel's uptime", age); |
| 289 | }, |
| 290 | _ => panic!("no stat for the sleep or for init"), |
| 291 | } |
| 292 | } |
| 293 | } |