Skip to content

Commit 905833b

Browse files
HoTT-stuffclaude
andcommitted
feat(job): reap ended background jobs and release their process substitutions
A background job's substitutions went to a detached thread that waited without releasing, so one that the job never opened stayed blocked until exit and left a FIFO in /tmp. The job table now keeps them and reaps ended jobs with a non-blocking waitpid at each safe point: before every command, before each REPL prompt (with a Done notice), and in fg. A reaped job's substitutions go through ProcessSubstitution::cleanup(). A job keeps them while it runs, so a late reader still gets its input. The detached thread (cleanup_when_consumed) is removed. At exit, ended jobs are reaped and released. A job that still runs keeps its FIFO, and the exit does not wait for it (marked snip in job.rs). Tests: three JobTable unit tests, three binary tests, and the late-reader unit test now goes through the job table. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0136P7ZpKjBuoCRahUbNPywX
1 parent 6b37edc commit 905833b

9 files changed

Lines changed: 457 additions & 52 deletions

File tree

‎impl/rust-cli/src/commands.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1767,7 +1767,13 @@ pub fn fg(state: &mut ShellState, job_spec: Option<&str>) -> Result<()> {
17671767
job_cmd.trim_end_matches(" &")
17681768
);
17691769
} else {
1770-
// Job completed - remove from table
1770+
// Job completed: nothing can open its FIFOs now, so release the
1771+
// process substitutions it held, then remove it from the table.
1772+
for sub in state.jobs.take_process_subs(job_id) {
1773+
if let Err(e) = sub.cleanup() {
1774+
eprintln!("Warning: Failed to cleanup process substitution: {}", e);
1775+
}
1776+
}
17711777
state.jobs.remove_job(job_id);
17721778
}
17731779
}

‎impl/rust-cli/src/enhanced_repl.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,12 @@ pub fn run(state: &mut ShellState) -> Result<()> {
291291
let mut accumulated_input = String::new();
292292

293293
loop {
294+
// Report the background jobs that ended since the last prompt.
295+
state.reap_jobs();
296+
for notice in state.job_notices.drain(..) {
297+
println!("{notice}");
298+
}
299+
294300
// Build prompt
295301
let txn_name = state.active_transaction.as_ref().map(|t| t.name.clone());
296302
let undo_count = state.history.iter().filter(|o| !o.undone).count();

‎impl/rust-cli/src/executable.rs‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,9 @@ pub enum ExecutionResult {
7272

7373
impl ExecutableCommand for Command {
7474
fn execute(&self, state: &mut ShellState) -> Result<ExecutionResult> {
75+
// Safe point: collect the background jobs that have ended, and
76+
// release their process substitutions, before the next command runs.
77+
state.reap_jobs();
7578
match self {
7679
// Filesystem operations (reversible)
7780
Command::Mkdir { path, redirects } => {
@@ -521,9 +524,12 @@ impl ExecutableCommand for Command {
521524
redirects,
522525
state,
523526
) {
524-
// The job may open a FIFO later: do not release or
525-
// remove one that it has not read yet.
526-
Ok(_job_id) => expansion.cleanup_when_consumed(),
527+
// The job may open a FIFO later: the job table keeps
528+
// the substitutions and releases them when it reaps
529+
// the job.
530+
Ok(job_id) => state
531+
.jobs
532+
.attach_process_subs(job_id, expansion.process_subs),
527533
// No job: nothing will open the FIFOs.
528534
Err(e) => {
529535
eprintln!("{}: {}", expanded_program, e);

‎impl/rust-cli/src/job.rs‎

Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
//! - Job specifications (%1, %+, %-, %name, %?pattern)
1212
//! - Current and previous job markers
1313
14+
use crate::process_sub::ProcessSubstitution;
15+
1416
/// Job state
1517
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1618
pub enum JobState {
@@ -45,6 +47,19 @@ pub struct Job {
4547
pub state: JobState,
4648
/// PIDs in this job (for pipelines)
4749
pub pids: Vec<i32>,
50+
/// PIDs of this job that have been reaped (ended and collected)
51+
reaped: Vec<i32>,
52+
}
53+
54+
/// A job that has ended, with the process substitutions it still held.
55+
#[derive(Debug)]
56+
pub struct FinishedJob {
57+
/// Job ID
58+
pub id: usize,
59+
/// Command string for display
60+
pub command: String,
61+
/// The substitutions to release now that nothing can open them
62+
pub process_subs: Vec<ProcessSubstitution>,
4863
}
4964

5065
/// Job table managing all jobs
@@ -54,6 +69,9 @@ pub struct JobTable {
5469
next_id: usize,
5570
current_job_id: Option<usize>, // %+ marker
5671
previous_job_id: Option<usize>, // %- marker
72+
/// Process substitutions that a job may still open, by job id. They live
73+
/// here, not in [`Job`], because a substitution cannot be cloned.
74+
process_subs: std::collections::HashMap<usize, Vec<ProcessSubstitution>>,
5775
}
5876

5977
impl JobTable {
@@ -64,6 +82,7 @@ impl JobTable {
6482
next_id: 1,
6583
current_job_id: None,
6684
previous_job_id: None,
85+
process_subs: std::collections::HashMap::new(),
6786
}
6887
}
6988

@@ -78,6 +97,7 @@ impl JobTable {
7897
command,
7998
state: JobState::Running,
8099
pids,
100+
reaped: Vec::new(),
81101
};
82102

83103
self.jobs.push(job);
@@ -135,6 +155,9 @@ impl JobTable {
135155
/// Remove job from table
136156
pub fn remove_job(&mut self, id: usize) {
137157
self.jobs.retain(|j| j.id != id);
158+
// A substitution that is still here belongs to a job that is gone:
159+
// dropping it ends its child and removes its FIFO.
160+
self.process_subs.remove(&id);
138161

139162
// Update markers if removed job was current/previous
140163
if self.current_job_id == Some(id) {
@@ -181,6 +204,81 @@ impl JobTable {
181204
lines
182205
}
183206

207+
/// Keep the process substitutions of a job until it ends: the job may open
208+
/// a FIFO at any later time, so nothing is released while it runs.
209+
pub fn attach_process_subs(&mut self, id: usize, subs: Vec<ProcessSubstitution>) {
210+
if subs.is_empty() {
211+
return;
212+
}
213+
self.process_subs.entry(id).or_default().extend(subs);
214+
}
215+
216+
/// Take the process substitutions of a job, for a caller that has seen the
217+
/// job end (`fg` waits for it itself).
218+
pub fn take_process_subs(&mut self, id: usize) -> Vec<ProcessSubstitution> {
219+
self.process_subs.remove(&id).unwrap_or_default()
220+
}
221+
222+
/// The `+` or `-` marker of a job, or a space.
223+
pub fn marker(&self, id: usize) -> char {
224+
if self.current_job_id == Some(id) {
225+
'+'
226+
} else if self.previous_job_id == Some(id) {
227+
'-'
228+
} else {
229+
' '
230+
}
231+
}
232+
233+
/// Reap the running jobs that have ended, without blocking.
234+
///
235+
/// Each process of a running job is polled with `waitpid(WNOHANG)`. A job
236+
/// whose processes have all ended is marked [`JobState::Done`] and returned
237+
/// once, with the process substitutions it held. The job stays in the table
238+
/// until [`JobTable::remove_job`]. The caller releases the substitutions.
239+
#[cfg(unix)]
240+
pub fn reap_finished(&mut self) -> Vec<FinishedJob> {
241+
let mut finished = Vec::new();
242+
for job in &mut self.jobs {
243+
if job.state != JobState::Running {
244+
continue;
245+
}
246+
for &pid in &job.pids {
247+
if job.reaped.contains(&pid) {
248+
continue;
249+
}
250+
let mut status: i32 = 0;
251+
// SAFETY: `status` is a live, exclusively borrowed i32 for the
252+
// whole call; waitpid writes the child's status into it and
253+
// nothing else. WNOHANG makes the call return at once.
254+
let reaped = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) };
255+
// 0: still running. A pid or -1 (no such child: someone else
256+
// already collected it): it has ended.
257+
if reaped != 0 {
258+
job.reaped.push(pid);
259+
}
260+
}
261+
if job.pids.iter().all(|pid| job.reaped.contains(pid)) {
262+
job.state = JobState::Done;
263+
finished.push((job.id, job.command.clone()));
264+
}
265+
}
266+
finished
267+
.into_iter()
268+
.map(|(id, command)| FinishedJob {
269+
id,
270+
command,
271+
process_subs: self.process_subs.remove(&id).unwrap_or_default(),
272+
})
273+
.collect()
274+
}
275+
276+
/// Job control needs Unix process groups; nothing is reaped elsewhere.
277+
#[cfg(not(unix))]
278+
pub fn reap_finished(&mut self) -> Vec<FinishedJob> {
279+
Vec::new()
280+
}
281+
184282
/// Get all jobs
185283
pub fn jobs(&self) -> &[Job] {
186284
&self.jobs
@@ -193,9 +291,97 @@ impl Default for JobTable {
193291
}
194292
}
195293

294+
/// When the shell exits, release the substitutions of the jobs that have
295+
/// ended. A job that is still running may open its FIFO later, so its
296+
/// substitutions are left alone: dropping one would end its child and remove
297+
/// the FIFO under the job.
298+
// snip: a substitution of a job that still runs at exit is never released.
299+
// Its FIFO stays in the temp directory, and its child stays blocked until the
300+
// job opens the FIFO. The exit does not wait for the job.
301+
impl Drop for JobTable {
302+
fn drop(&mut self) {
303+
for finished in self.reap_finished() {
304+
for sub in finished.process_subs {
305+
if let Err(e) = sub.cleanup() {
306+
eprintln!("Warning: Failed to cleanup process substitution: {}", e);
307+
}
308+
}
309+
}
310+
for (_, subs) in self.process_subs.drain() {
311+
for sub in subs {
312+
std::mem::forget(sub);
313+
}
314+
}
315+
}
316+
}
317+
196318
#[cfg(test)]
197319
mod tests {
198320
use super::*;
321+
use std::process::Command;
322+
use std::time::{Duration, Instant};
323+
324+
/// Reap until `id` has ended, for at most ten seconds.
325+
fn reap_until_done(table: &mut JobTable, id: usize) -> Vec<FinishedJob> {
326+
let started = Instant::now();
327+
loop {
328+
let finished = table.reap_finished();
329+
if finished.iter().any(|job| job.id == id) {
330+
return finished;
331+
}
332+
assert!(
333+
started.elapsed() < Duration::from_secs(10),
334+
"job did not end"
335+
);
336+
std::thread::sleep(Duration::from_millis(10));
337+
}
338+
}
339+
340+
#[test]
341+
fn reap_marks_a_finished_job_done_and_returns_it() {
342+
// The reaper under test collects the child, so no handle is kept.
343+
let pid = Command::new("true").spawn().unwrap().id() as i32;
344+
let mut table = JobTable::new();
345+
let id = table.add_job(pid, "true &".to_string(), vec![pid]);
346+
let finished = reap_until_done(&mut table, id);
347+
assert_eq!(finished.len(), 1);
348+
assert_eq!(finished[0].command, "true &");
349+
assert_eq!(table.jobs()[0].state, JobState::Done);
350+
// A job is reported once.
351+
assert!(table.reap_finished().is_empty());
352+
}
353+
354+
#[test]
355+
fn reap_leaves_a_running_job_alone() {
356+
let mut child = Command::new("sleep").arg("30").spawn().unwrap();
357+
let pid = child.id() as i32;
358+
let mut table = JobTable::new();
359+
table.add_job(pid, "sleep 30 &".to_string(), vec![pid]);
360+
assert!(table.reap_finished().is_empty());
361+
assert_eq!(table.jobs()[0].state, JobState::Running);
362+
child.kill().unwrap();
363+
child.wait().unwrap();
364+
}
365+
366+
#[test]
367+
fn a_pipeline_job_ends_when_all_its_processes_have_ended() {
368+
let quick_pid = Command::new("true").spawn().unwrap().id() as i32;
369+
let mut slow = Command::new("sleep").arg("30").spawn().unwrap();
370+
let slow_pid = slow.id() as i32;
371+
let mut table = JobTable::new();
372+
table.add_job(
373+
quick_pid,
374+
"true | sleep 30 &".to_string(),
375+
vec![quick_pid, slow_pid],
376+
);
377+
std::thread::sleep(Duration::from_millis(200));
378+
assert!(table.reap_finished().is_empty());
379+
assert_eq!(table.jobs()[0].state, JobState::Running);
380+
slow.kill().unwrap();
381+
slow.wait().unwrap();
382+
let finished = reap_until_done(&mut table, 1);
383+
assert_eq!(finished.len(), 1);
384+
}
199385

200386
#[test]
201387
fn test_add_job() {

0 commit comments

Comments
 (0)