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 ) ]
1618pub 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
5977impl 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) ]
197319mod 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