subprocess 1.0.3

Execution and control of child processes and pipelines.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
use std::fs::{self, File};
use std::io::{self, ErrorKind, prelude::*};
use std::time::{Duration, Instant};

use tempfile::TempDir;

use crate::{Exec, Redirection};

// --- Single-command Job tests ---

#[test]
fn exec_start() {
    let mut handle = Exec::cmd("echo")
        .arg("hello")
        .stdout(Redirection::Pipe)
        .start()
        .unwrap();
    let output = io::read_to_string(handle.stdout.take().unwrap()).unwrap();
    assert!(output.contains("hello"));
}

#[test]
fn exec_start_capture() {
    let c = Exec::cmd("echo")
        .arg("hello")
        .stdout(Redirection::Pipe)
        .start()
        .unwrap()
        .capture()
        .unwrap();
    assert!(c.stdout_str().contains("hello"));
}

#[test]
fn exec_start_join() {
    let status = Exec::cmd("true").start().unwrap().join().unwrap();
    assert!(status.success());

    let status = Exec::cmd("false").start().unwrap().join().unwrap();
    assert!(!status.success());
}

#[test]
fn exec_start_stdin_write() {
    let mut handle = Exec::cmd("cat")
        .stdin(Redirection::Pipe)
        .stdout(Redirection::Pipe)
        .start()
        .unwrap();
    handle
        .stdin
        .as_mut()
        .unwrap()
        .write_all(b"hello world")
        .unwrap();
    handle.stdin.take(); // close stdin to let cat finish
    let output = io::read_to_string(handle.stdout.take().unwrap()).unwrap();
    assert_eq!(output, "hello world");
}

#[test]
fn exec_start_stderr() {
    let mut handle = Exec::cmd("sh")
        .args(&["-c", "echo err-output >&2"])
        .stderr(Redirection::Pipe)
        .start()
        .unwrap();
    let stderr = io::read_to_string(handle.stderr.take().unwrap()).unwrap();
    assert_eq!(stderr.trim(), "err-output");
}

#[test]
fn exec_start_stdin_data_capture() {
    // stdin_data set via .stdin("data") is moved into Job and correctly
    // fed through communicate in the capture path.
    let c = Exec::cmd("cat")
        .stdin("hello from stdin_data")
        .stdout(Redirection::Pipe)
        .start()
        .unwrap()
        .capture()
        .unwrap();
    assert_eq!(c.stdout_str(), "hello from stdin_data");
}

#[test]
fn read_from_stdout() {
    let mut handle = Exec::cmd("echo")
        .arg("foo")
        .stdout(Redirection::Pipe)
        .start()
        .unwrap();
    assert_eq!(
        io::read_to_string(handle.stdout.take().unwrap()).unwrap(),
        "foo\n"
    );
    assert!(handle.wait().unwrap().success());
}

#[test]
fn input_from_file() {
    let tmpdir = TempDir::new().unwrap();
    let tmpname = tmpdir.path().join("input");
    {
        let mut outfile = File::create(&tmpname).unwrap();
        outfile.write_all(b"foo").unwrap();
    }
    let mut handle = Exec::cmd("cat")
        .arg(tmpname.to_str().unwrap())
        .stdin(File::open(&tmpname).unwrap())
        .stdout(Redirection::Pipe)
        .start()
        .unwrap();
    assert_eq!(
        io::read_to_string(handle.stdout.take().unwrap()).unwrap(),
        "foo"
    );
    assert!(handle.wait().unwrap().success());
}

#[test]
fn output_to_file() {
    let tmpdir = TempDir::new().unwrap();
    let tmpname = tmpdir.path().join("output");
    let outfile = File::create(&tmpname).unwrap();
    let status = Exec::cmd("printf")
        .arg("foo")
        .stdout(outfile)
        .start()
        .unwrap()
        .wait()
        .unwrap();
    assert!(status.success());
    assert_eq!(fs::read_to_string(&tmpname).unwrap(), "foo");
}

#[test]
fn input_output_from_file() {
    let tmpdir = TempDir::new().unwrap();
    let tmpname_in = tmpdir.path().join("input");
    let tmpname_out = tmpdir.path().join("output");
    {
        let mut f = File::create(&tmpname_in).unwrap();
        f.write_all(b"foo").unwrap();
    }
    let status = Exec::cmd("cat")
        .stdin(File::open(&tmpname_in).unwrap())
        .stdout(File::create(&tmpname_out).unwrap())
        .start()
        .unwrap()
        .wait()
        .unwrap();
    assert!(status.success());
    assert_eq!(fs::read_to_string(&tmpname_out).unwrap(), "foo");
}

#[test]
fn write_to_subprocess() {
    let tmpdir = TempDir::new().unwrap();
    let tmpname = tmpdir.path().join("output");
    let mut handle = Exec::cmd("uniq")
        .stdin(Redirection::Pipe)
        .stdout(File::create(&tmpname).unwrap())
        .start()
        .unwrap();
    handle
        .stdin
        .take()
        .unwrap()
        .write_all(b"foo\nfoo\nbar\n")
        .unwrap();
    assert!(handle.wait().unwrap().success());
    assert_eq!(fs::read_to_string(tmpname).unwrap(), "foo\nbar\n");
}

#[test]
fn merge_err_to_out_pipe() {
    let mut handle = Exec::cmd("sh")
        .args(&["-c", "echo foo; echo bar >&2"])
        .stdout(Redirection::Pipe)
        .stderr(Redirection::Merge)
        .start()
        .unwrap();
    let (out, err) = handle.communicate().unwrap().read().unwrap();
    assert_eq!(out, b"foo\nbar\n");
    assert!(err.is_empty());
    assert!(handle.wait().unwrap().success());
}

#[test]
fn merge_out_to_err_pipe() {
    let mut handle = Exec::cmd("sh")
        .args(&["-c", "echo foo; echo bar >&2"])
        .stdout(Redirection::Merge)
        .stderr(Redirection::Pipe)
        .start()
        .unwrap();
    let (out, err) = handle.communicate().unwrap().read().unwrap();
    assert!(out.is_empty());
    assert_eq!(err, b"foo\nbar\n");
    assert!(handle.wait().unwrap().success());
}

#[test]
fn merge_err_to_out_file() {
    let tmpdir = TempDir::new().unwrap();
    let tmpname = tmpdir.path().join("output");
    let status = Exec::cmd("sh")
        .args(&["-c", "printf foo; printf bar >&2"])
        .stdout(File::create(&tmpname).unwrap())
        .stderr(Redirection::Merge)
        .start()
        .unwrap()
        .wait()
        .unwrap();
    assert!(status.success());
    assert_eq!(fs::read_to_string(&tmpname).unwrap(), "foobar");
}

#[test]
fn broken_pipe_on_stdin() {
    // Child exits immediately without reading stdin
    let mut handle = Exec::cmd("true").stdin(Redirection::Pipe).start().unwrap();
    // Try to write data - the child exits without reading, causing
    // broken pipe
    let large_data = vec![0u8; 100_000];
    // Write may succeed or fail with BrokenPipe, but must not hang
    let _ = handle.stdin.as_mut().unwrap().write_all(&large_data);
    drop(handle.stdin.take());
    // Process should still be waitable
    handle.wait().unwrap();
}

// --- Process lifecycle tests (via Job) ---

#[test]
fn terminate() {
    let start = Instant::now();
    let handle = Exec::cmd("sleep").arg("10").start().unwrap();
    handle.terminate().unwrap();
    handle.wait().unwrap();
    assert!(
        start.elapsed() < Duration::from_secs(5),
        "terminate too slow"
    );
}

#[test]
fn terminate_twice() {
    use std::thread;

    let start = Instant::now();
    let handle = Exec::cmd("sleep").arg("10").start().unwrap();
    handle.terminate().unwrap();
    thread::sleep(Duration::from_millis(100));
    handle.terminate().unwrap();
    handle.wait().unwrap();
    assert!(
        start.elapsed() < Duration::from_secs(5),
        "terminate too slow"
    );
}

#[test]
fn terminate_after_exit() {
    let job = Exec::cmd("true").start().unwrap();
    job.wait().unwrap();
    // Should be no-op, not error
    job.terminate().unwrap();
    job.kill().unwrap();
}

#[test]
fn pid_while_running() {
    let job = Exec::cmd("sleep").arg("10").start().unwrap();
    // pid() returns u32 always, verify it is nonzero while running
    assert!(job.pid() > 0, "pid() should be nonzero while running");
    assert!(
        job.processes[0].exit_status().is_none(),
        "exit_status() should be None while running"
    );
    job.terminate().unwrap();
    job.wait().unwrap();
    // pid is still available after exit
    assert!(job.pid() > 0, "pid() should still be nonzero after exit");
    assert!(
        job.processes[0].exit_status().is_some(),
        "exit_status() should be Some after exit"
    );
}

#[test]
fn poll_running_process() {
    let job = Exec::cmd("sleep").arg("10").start().unwrap();
    assert!(
        job.poll().is_none(),
        "poll() should return None for running process"
    );
    job.terminate().unwrap();
    job.wait().unwrap();
    assert!(
        job.poll().is_some(),
        "poll() should return Some after process finished"
    );
}

#[test]
fn poll_finished_process() {
    let job = Exec::cmd("true").start().unwrap();
    job.wait().unwrap();
    assert!(job.poll().unwrap().success());
    // Multiple polls should return the same result
    assert!(job.poll().unwrap().success());
}

#[test]
fn wait_multiple_times() {
    let job = Exec::cmd("sh").args(&["-c", "exit 42"]).start().unwrap();
    let s1 = job.wait().unwrap();
    let s2 = job.wait().unwrap();
    let s3 = job.wait().unwrap();
    assert_eq!(s1.code(), Some(42));
    assert_eq!(s1, s2);
    assert_eq!(s2, s3);
}

#[test]
fn wait_timeout() {
    let job = Exec::cmd("sleep").arg("0.5").start().unwrap();
    let ret = job.wait_timeout(Duration::from_millis(100)).unwrap();
    assert!(ret.is_none());
    // Sleep for a very long time to avoid flaky failures when we get a
    // slow machine that takes too long to start sleep(1).
    let ret = job.wait_timeout(Duration::from_millis(900)).unwrap();
    assert!(ret.unwrap().success());
}

#[test]
fn wait_timeout_zero() {
    let job = Exec::cmd("sleep").arg("10").start().unwrap();
    // Zero timeout should return immediately
    let start = Instant::now();
    let result = job.wait_timeout(Duration::ZERO).unwrap();
    assert!(
        start.elapsed() < Duration::from_millis(100),
        "zero timeout took too long"
    );
    assert!(result.is_none());
    job.terminate().unwrap();
    job.wait().unwrap();
}

#[test]
fn wait_timeout_already_finished() {
    let job = Exec::cmd("true").start().unwrap();
    job.wait().unwrap();
    // Timeout on finished process should return immediately with cached
    // status
    let start = Instant::now();
    let result = job.wait_timeout(Duration::from_secs(10)).unwrap();
    assert!(
        start.elapsed() < Duration::from_millis(100),
        "wait_timeout on finished process took too long"
    );
    assert!(result.unwrap().success());
}

#[test]
fn detach_does_not_wait_on_drop() {
    let start = Instant::now();
    {
        let handle = Exec::cmd("sleep").arg("10").detached().start().unwrap();
        // handle and its processes are dropped here without waiting
        drop(handle);
    }
    // Should return almost immediately, not wait 10 seconds
    assert!(
        start.elapsed() < Duration::from_secs(1),
        "detach() didn't prevent waiting on drop"
    );
}

// --- Job timeout tests ---

#[test]
fn capture_timeout() {
    match Exec::cmd("sleep")
        .args(&["0.5"])
        .start()
        .unwrap()
        .capture_timeout(Duration::from_millis(100))
    {
        Ok(_) => panic!("expected timeout return"),
        Err(e) => match e.kind() {
            ErrorKind::TimedOut => assert!(true),
            _ => panic!("expected timeout return"),
        },
    }
}

#[test]
fn exec_timeout_join_timed_out() {
    let result = Exec::cmd("sleep")
        .arg("0.5")
        .start()
        .unwrap()
        .join_timeout(Duration::from_millis(100));
    assert_eq!(result.unwrap_err().kind(), ErrorKind::TimedOut);
}

#[test]
fn exec_timeout_join_succeeds() {
    let status = Exec::cmd("true")
        .start()
        .unwrap()
        .join_timeout(Duration::from_secs(5))
        .unwrap();
    assert!(status.success());
}

#[test]
fn exec_wait_timeout_terminate() {
    let started = Exec::cmd("sleep").arg("10").start().unwrap();
    let result = started.wait_timeout(Duration::from_millis(100)).unwrap();
    assert!(result.is_none());
    started.terminate().unwrap();
    let status = started.wait().unwrap();
    assert!(!status.success());
}

// --- Job convenience method tests ---

#[test]
fn started_pid() {
    let start = Instant::now();
    let job = Exec::cmd("sleep").arg("10").start().unwrap();
    assert!(job.pid() > 0, "pid() should be nonzero");
    job.terminate().unwrap();
    job.wait().unwrap();
    assert!(
        start.elapsed() < Duration::from_secs(5),
        "terminate too slow"
    );
}

#[test]
fn started_kill() {
    let handle = Exec::cmd("sleep").arg("10").start().unwrap();
    handle.kill().unwrap();
    let status = handle.wait().unwrap();
    assert!(!status.success());
}

#[test]
fn started_poll() {
    let start = Instant::now();
    let job = Exec::cmd("sleep").arg("10").start().unwrap();
    assert!(job.poll().is_none(), "poll() should be None while running");
    job.terminate().unwrap();
    job.wait().unwrap();
    assert!(job.poll().is_some(), "poll() should be Some after finished");
    assert!(
        start.elapsed() < Duration::from_secs(5),
        "terminate too slow"
    );
}

#[test]
fn started_wait_timeout_none() {
    let start = Instant::now();
    let handle = Exec::cmd("sleep").arg("10").start().unwrap();
    let result = handle.wait_timeout(Duration::from_millis(100)).unwrap();
    assert!(result.is_none(), "should return None on timeout");
    handle.terminate().unwrap();
    handle.wait().unwrap();
    assert!(
        start.elapsed() < Duration::from_secs(5),
        "terminate too slow"
    );
}

#[test]
fn started_wait_timeout_some() {
    let handle = Exec::cmd("true").start().unwrap();
    let result = handle.wait_timeout(Duration::from_secs(5)).unwrap();
    assert!(result.is_some(), "should return Some when done");
    assert!(result.unwrap().success());
}

// --- Pipeline Job tests ---

#[test]
fn pipeline_detached() {
    let start = Instant::now();
    {
        let _handle = { Exec::cmd("sleep").arg("10") | Exec::cmd("sleep").arg("10") }
            .detached()
            .start()
            .unwrap();
        // handle and its processes are dropped here without waiting
    }
    assert!(
        start.elapsed() < Duration::from_secs(1),
        "detached() didn't prevent waiting on drop"
    );
}

#[test]
fn pipeline_start() {
    let mut handle = { Exec::cmd("echo").arg("foo\nbar") | Exec::cmd("wc").arg("-l") }
        .stdout(Redirection::Pipe)
        .start()
        .unwrap();
    let output = io::read_to_string(handle.stdout.take().unwrap()).unwrap();
    assert_eq!(output.trim(), "2");
}

#[test]
fn pipeline_start_processes_accessible() {
    let handle = { Exec::cmd("echo").arg("foo") | Exec::cmd("cat") }
        .start()
        .unwrap();
    let status = handle.processes.last().unwrap().wait().unwrap();
    assert!(status.success());
}

#[test]
fn pipeline_start_join() {
    let status = { Exec::cmd("echo").arg("hi") | Exec::cmd("cat") }
        .start()
        .unwrap()
        .join()
        .unwrap();
    assert!(status.success());
}

#[test]
fn pipeline_start_stdin_write() {
    let mut handle = { Exec::cmd("cat") | Exec::cmd("cat") }
        .stdin(Redirection::Pipe)
        .stdout(Redirection::Pipe)
        .start()
        .unwrap();
    handle
        .stdin
        .as_mut()
        .unwrap()
        .write_all(b"piped data")
        .unwrap();
    handle.stdin.take(); // close stdin
    let output = io::read_to_string(handle.stdout.take().unwrap()).unwrap();
    assert_eq!(output, "piped data");
}

#[test]
fn pipeline_start_stdin_data_capture() {
    // stdin_data flows through pipeline's start+capture path.
    let c = { Exec::cmd("cat") | Exec::cmd("cat") }
        .stdin("hello from pipeline")
        .stdout(Redirection::Pipe)
        .start()
        .unwrap()
        .capture()
        .unwrap();
    assert_eq!(c.stdout_str(), "hello from pipeline");
}

#[test]
fn pipeline_start_capture_no_pipes() {
    // start() does no auto-setup, so without explicit pipes, capture() gets
    // nothing - process output goes to the parent's stdout (inherited).
    let c = { Exec::cmd("echo").arg("hello") | Exec::cmd("cat") }
        .start()
        .unwrap()
        .capture()
        .unwrap();
    assert_eq!(c.stdout_str(), "");
    assert_eq!(c.stderr_str(), "");
}

#[test]
fn pipeline_start_capture_stdout_only() {
    // With start(), only explicitly set pipes produce data.  Here stdout is
    // piped but stderr is not, so stderr is empty.  Compare to
    // pipeline.capture() which would auto-set stderr_all(Pipe).
    let c = { Exec::cmd("sh").arg("-c").arg("echo out; echo err >&2") | Exec::cmd("cat") }
        .stdout(Redirection::Pipe)
        .start()
        .unwrap()
        .capture()
        .unwrap();
    assert!(
        c.stdout_str().contains("out"),
        "stdout should contain 'out', got: {:?}",
        c.stdout_str()
    );
    assert_eq!(c.stderr_str(), "");
}

#[test]
fn pipeline_start_communicate_needs_explicit_pipes() {
    // start() doesn't auto-set pipes - you must configure them explicitly.
    // Here we set stdout(Pipe) and verify the communicator reads from it.
    let mut handle = { Exec::cmd("echo").arg("foo") | Exec::cmd("cat") }
        .stdout(Redirection::Pipe)
        .start()
        .unwrap();
    let mut comm = handle.communicate().unwrap();
    let (stdout, stderr) = comm.read().unwrap();
    assert_eq!(String::from_utf8_lossy(&stdout).trim(), "foo");
    assert_eq!(stderr, b"");
}

#[test]
fn pipeline_stderr_all_pipe_start() {
    // stderr(Pipe) with start() provides the shared stderr read end.
    let mut handle = {
        Exec::cmd("sh").arg("-c").arg("echo err1 >&2; echo out1")
            | Exec::cmd("sh").arg("-c").arg("cat; echo err2 >&2")
    }
    .stdout(Redirection::Pipe)
    .stderr_all(Redirection::Pipe)
    .start()
    .unwrap();

    let stdout = io::read_to_string(handle.stdout.take().unwrap()).unwrap();
    let stderr = io::read_to_string(handle.stderr.take().unwrap()).unwrap();
    assert!(stdout.contains("out1"), "stdout: {:?}", stdout);
    assert!(stderr.contains("err1"), "stderr: {:?}", stderr);
    assert!(stderr.contains("err2"), "stderr: {:?}", stderr);
}

#[test]
fn pipeline_capture_timeout() {
    match (Exec::cmd("sleep").arg("0.5") | Exec::cmd("cat"))
        .start()
        .unwrap()
        .capture_timeout(Duration::from_millis(100))
    {
        Ok(_) => panic!("expected timeout return"),
        Err(e) => assert_eq!(e.kind(), ErrorKind::TimedOut),
    }
}

#[test]
fn pipeline_timeout_join_timed_out() {
    let result = (Exec::cmd("sleep").arg("0.5") | Exec::cmd("cat"))
        .start()
        .unwrap()
        .join_timeout(Duration::from_millis(100));
    assert_eq!(result.unwrap_err().kind(), ErrorKind::TimedOut);
}