1use std::io::Read;
2use std::process::{Child, Output};
3use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, Ordering};
5
6pub struct LimitedProcessOutput {
19 pub output: Output,
20 pub completeness: crate::core::context_admission::OutputCompleteness,
21}
22
23#[cfg(test)]
26pub(crate) fn wait_with_limits(
27 child: Child,
28 max_bytes: usize,
29 timeout: std::time::Duration,
30 kill_group: bool,
31) -> Output {
32 wait_with_limits_captured(child, max_bytes, timeout, kill_group).output
33}
34
35pub fn wait_with_limits_captured(
36 mut child: Child,
37 max_bytes: usize,
38 timeout: std::time::Duration,
39 kill_group: bool,
40) -> LimitedProcessOutput {
41 const STDERR_LIMIT: usize = 512 * 1024;
42 const DRAIN_GRACE: std::time::Duration = std::time::Duration::from_millis(250);
45 const READER_BUDGET: std::time::Duration = std::time::Duration::from_secs(2);
47 const REAP_BUDGET: std::time::Duration = std::time::Duration::from_secs(2);
49
50 let own_group = owned_group(&mut child, kill_group);
54
55 let stdout_pipe = child.stdout.take();
56 let stderr_pipe = child.stderr.take();
57 let start = std::time::Instant::now();
58 let truncated = Arc::new(AtomicBool::new(false));
59 let read_failed = Arc::new(AtomicBool::new(false));
60
61 let stdout_capture = Arc::new(StreamCapture::default());
65 let stderr_capture = Arc::new(StreamCapture::default());
66 let stdout_handle = std::thread::spawn({
67 let (capture, truncated, read_failed) = (
68 Arc::clone(&stdout_capture),
69 Arc::clone(&truncated),
70 Arc::clone(&read_failed),
71 );
72 move || read_stream(stdout_pipe, max_bytes, &capture, &truncated, &read_failed)
73 });
74 let stderr_handle = std::thread::spawn({
75 let (capture, truncated, read_failed) = (
76 Arc::clone(&stderr_capture),
77 Arc::clone(&truncated),
78 Arc::clone(&read_failed),
79 );
80 move || {
81 read_stream(
82 stderr_pipe,
83 STDERR_LIMIT,
84 &capture,
85 &truncated,
86 &read_failed,
87 );
88 }
89 });
90
91 let mut timed_out = false;
92 let mut wait_failed = false;
93 let mut kill_failed = false;
94 let mut forced_pipe_cleanup = false;
95 loop {
96 let hit_timeout = start.elapsed() > timeout;
97 if hit_timeout || truncated.load(Ordering::Relaxed) {
98 kill_failed |= !kill_child(&mut child, own_group);
100 timed_out = hit_timeout;
101 break;
102 }
103 match exited_unreaped(&mut child) {
104 Ok(true) => {
105 if own_group.is_some()
110 && !readers_finish_within(&stdout_handle, &stderr_handle, DRAIN_GRACE)
111 {
112 kill_failed |= !kill_child(&mut child, own_group);
113 forced_pipe_cleanup = true;
114 }
115 break;
116 }
117 Err(_) => {
118 wait_failed = true;
119 kill_failed |= !kill_child(&mut child, own_group);
120 break;
121 }
122 Ok(false) => std::thread::sleep(std::time::Duration::from_millis(50)),
123 }
124 }
125
126 let reaped = reap_within(&mut child, REAP_BUDGET);
131
132 let readers_finished = readers_finish_within(&stdout_handle, &stderr_handle, READER_BUDGET);
139 let reader_join_failed =
140 !readers_finished || stdout_handle.join().is_err() || stderr_handle.join().is_err();
141 let (mut stdout_buf, stdout_truncated) = stdout_capture.take();
142 let (mut stderr_buf, stderr_truncated) = stderr_capture.take();
143 let decode_lossy =
144 std::str::from_utf8(&stdout_buf).is_err() || std::str::from_utf8(&stderr_buf).is_err();
145 let reader_incomplete = wait_failed
146 || kill_failed
147 || reaped.is_none()
148 || forced_pipe_cleanup
149 || read_failed.load(Ordering::Relaxed)
150 || reader_join_failed;
151
152 if timed_out || stdout_truncated {
153 stdout_buf.extend_from_slice(output_limit_notice(max_bytes, timeout).as_bytes());
154 }
155 if stderr_truncated {
156 let notice = format!(
157 "\n[lean-ctx: stderr truncated at {} KB limit]\n",
158 STDERR_LIMIT / 1024
159 );
160 stderr_buf.extend_from_slice(notice.as_bytes());
161 }
162 if !readers_finished {
163 stdout_buf.extend_from_slice(
164 b"\n[lean-ctx: output not captured: a process outside this call kept it open]\n",
165 );
166 }
167
168 if reaped.is_none() {
169 stdout_buf.extend_from_slice(
170 b"\n[lean-ctx: the process could not be ended within the cleanup budget]\n",
171 );
172 }
173 let status = reaped.unwrap_or_else(synthetic_failure_status);
174
175 LimitedProcessOutput {
176 output: Output {
177 status,
178 stdout: stdout_buf,
179 stderr: stderr_buf,
180 },
181 completeness: crate::core::context_admission::OutputCompleteness {
182 truncated: stdout_truncated || stderr_truncated || truncated.load(Ordering::Relaxed),
183 timed_out,
184 reader_incomplete,
185 cancelled: false,
186 decode_lossy,
187 },
188 }
189}
190
191pub fn output_limit_notice(max_bytes: usize, timeout: std::time::Duration) -> String {
193 format!(
194 "\n[lean-ctx: output truncated at {} MB / {}s limit]\n",
195 max_bytes / (1024 * 1024),
196 timeout.as_secs()
197 )
198}
199
200pub fn wait_inherited_with_timeout(
206 mut child: Child,
207 timeout: std::time::Duration,
208 kill_group: bool,
209) -> (std::process::ExitStatus, bool) {
210 const REAP_BUDGET: std::time::Duration = std::time::Duration::from_secs(2);
211 const MAX_POLL: std::time::Duration = std::time::Duration::from_millis(50);
212
213 let own_group = owned_group(&mut child, kill_group);
214 let start = std::time::Instant::now();
215 let mut poll = std::time::Duration::from_millis(1);
217 let mut timed_out = false;
218 loop {
219 if start.elapsed() > timeout {
220 kill_child(&mut child, own_group);
222 timed_out = true;
223 break;
224 }
225 match exited_unreaped(&mut child) {
226 Ok(true) => break,
227 Err(_) => {
228 kill_child(&mut child, own_group);
229 break;
230 }
231 Ok(false) => {
232 std::thread::sleep(poll.min(timeout.saturating_sub(start.elapsed())));
233 poll = (poll * 2).min(MAX_POLL);
234 }
235 }
236 }
237 let status = reap_within(&mut child, REAP_BUDGET).unwrap_or_else(synthetic_failure_status);
238 (status, timed_out)
239}
240
241#[derive(Default)]
245struct StreamCapture {
246 bytes: std::sync::Mutex<Vec<u8>>,
247 truncated: AtomicBool,
248}
249
250impl StreamCapture {
251 fn take(&self) -> (Vec<u8>, bool) {
255 let bytes = std::mem::take(
256 &mut *self
257 .bytes
258 .lock()
259 .unwrap_or_else(std::sync::PoisonError::into_inner),
260 );
261 (bytes, self.truncated.load(Ordering::Relaxed))
262 }
263}
264
265fn read_stream(
269 pipe: Option<impl Read>,
270 limit: usize,
271 capture: &StreamCapture,
272 any_truncated: &AtomicBool,
273 read_failed: &AtomicBool,
274) {
275 let Some(mut pipe) = pipe else {
276 read_failed.store(true, Ordering::Relaxed);
277 return;
278 };
279 let mut chunk = [0u8; 8192];
280 loop {
281 match pipe.read(&mut chunk) {
282 Ok(0) => return,
283 Ok(n) => {
284 let mut bytes = capture
285 .bytes
286 .lock()
287 .unwrap_or_else(std::sync::PoisonError::into_inner);
288 if bytes.len() + n > limit {
289 let remaining = limit.saturating_sub(bytes.len());
290 bytes.extend_from_slice(&chunk[..remaining]);
291 capture.truncated.store(true, Ordering::Relaxed);
292 any_truncated.store(true, Ordering::Relaxed);
293 return;
294 }
295 bytes.extend_from_slice(&chunk[..n]);
296 }
297 Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
298 Err(_) => {
299 read_failed.store(true, Ordering::Relaxed);
300 return;
301 }
302 }
303 }
304}
305
306#[cfg(unix)]
317fn owned_group(child: &mut Child, kill_group: bool) -> Option<i32> {
318 if !kill_group {
319 return None;
320 }
321 let pid = crate::ipc::process::group_target(child.id()).ok()?;
324 let group = unsafe { libc::getpgid(pid) };
327 if group == pid {
328 return Some(pid);
329 }
330 (group == -1 && matches!(exited_unreaped(child), Ok(true))).then_some(pid)
331}
332
333#[cfg(not(unix))]
334fn owned_group(_: &mut Child, _: bool) -> Option<i32> {
335 None
336}
337
338#[cfg(unix)]
340pub(crate) fn exited_unreaped(child: &mut Child) -> std::io::Result<bool> {
341 let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
343 let result = unsafe {
345 libc::waitid(
346 libc::P_PID,
347 child.id() as libc::id_t,
348 &raw mut info,
349 libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
350 )
351 };
352 if result == -1 {
353 let error = std::io::Error::last_os_error();
354 return if error.kind() == std::io::ErrorKind::Interrupted {
355 Ok(false)
356 } else {
357 Err(error)
358 };
359 }
360 Ok(unsafe { info.si_pid() } != 0)
362}
363
364#[cfg(not(unix))]
365fn exited_unreaped(child: &mut Child) -> std::io::Result<bool> {
366 child.try_wait().map(|status| status.is_some())
367}
368
369fn readers_finish_within<A, B>(
370 first: &std::thread::JoinHandle<A>,
371 second: &std::thread::JoinHandle<B>,
372 budget: std::time::Duration,
373) -> bool {
374 let deadline = std::time::Instant::now() + budget;
375 loop {
376 if first.is_finished() && second.is_finished() {
377 return true;
378 }
379 if std::time::Instant::now() >= deadline {
380 return false;
381 }
382 std::thread::sleep(std::time::Duration::from_millis(5));
383 }
384}
385
386fn kill_child(child: &mut Child, own_group: Option<i32>) -> bool {
396 #[cfg(unix)]
397 if let Some(group) = own_group {
398 unsafe { libc::killpg(group, libc::SIGKILL) };
400 }
401 #[cfg(not(unix))]
402 let _ = own_group;
403 #[cfg(windows)]
404 let tree_killed = {
405 const TREE_KILL_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);
406 match std::process::Command::new("taskkill")
407 .args(["/F", "/T", "/PID", &child.id().to_string()])
408 .stdin(std::process::Stdio::null())
409 .stdout(std::process::Stdio::null())
410 .stderr(std::process::Stdio::null())
411 .spawn()
412 {
413 Ok(mut tree_kill) => {
414 if let Some(status) = reap_within(&mut tree_kill, TREE_KILL_BUDGET) {
415 status.success()
416 } else {
417 let _ = tree_kill.kill();
418 let _ = reap_within(&mut tree_kill, TREE_KILL_BUDGET);
419 false
420 }
421 }
422 Err(_) => false,
423 }
424 };
425 #[cfg(not(windows))]
426 let tree_killed = true;
427 let _ = child.kill();
428 tree_killed
429}
430
431pub fn reap_within(
433 child: &mut Child,
434 budget: std::time::Duration,
435) -> Option<std::process::ExitStatus> {
436 let deadline = std::time::Instant::now() + budget;
437 loop {
438 match child.try_wait() {
439 Ok(Some(status)) => return Some(status),
440 Ok(None) if std::time::Instant::now() < deadline => {
441 std::thread::sleep(std::time::Duration::from_millis(5));
442 }
443 Ok(None) | Err(_) => return None,
444 }
445 }
446}
447
448#[cfg(unix)]
456fn synthetic_failure_status() -> std::process::ExitStatus {
457 use std::os::unix::process::ExitStatusExt;
458 std::process::ExitStatus::from_raw(1 << 8)
462}
463
464#[cfg(not(unix))]
465fn synthetic_failure_status() -> std::process::ExitStatus {
466 use std::os::windows::process::ExitStatusExt;
467 std::process::ExitStatus::from_raw(1)
468}
469
470#[cfg(test)]
471mod tests {
472 const OUTPUT_HELPER_ENV: &str = "LEAN_CTX_TEST_OUTPUT_HELPER";
473 const OUTPUT_HELPER_TEST: &str = "shell::exec::process::tests::wait_with_limits_output_helper";
474
475 #[test]
476 #[ignore = "subprocess helper for wait_with_limits tests"]
477 fn wait_with_limits_output_helper() {
478 use std::io::Write as _;
479
480 match std::env::var(OUTPUT_HELPER_ENV).as_deref() {
481 Ok("stdout-small") => {
482 std::io::stdout().write_all(b"hello\n").unwrap();
483 }
484 Ok("stdout-forever") => {
490 let chunk = [b'a'; 8192];
491 let mut stream = std::io::stdout().lock();
492 while stream.write_all(&chunk).is_ok() {}
493 std::thread::sleep(std::time::Duration::from_mins(1));
494 }
495 Ok("stderr-forever") => {
496 let chunk = [b'a'; 8192];
497 let mut stream = std::io::stderr().lock();
498 while stream.write_all(&chunk).is_ok() {}
499 std::thread::sleep(std::time::Duration::from_mins(1));
500 }
501 Ok("sleep") => {
502 std::thread::sleep(std::time::Duration::from_mins(1));
503 }
504 #[cfg(unix)]
505 Ok("guardian") => guardian(),
506 Ok(other) => panic!("unknown output helper mode: {other}"),
507 Err(error) => panic!("missing {OUTPUT_HELPER_ENV}: {error}"),
508 }
509 }
510
511 fn spawn_output_helper(mode: &str) -> std::process::Child {
512 std::process::Command::new(std::env::current_exe().unwrap())
513 .args([OUTPUT_HELPER_TEST, "--exact", "--ignored", "--nocapture"])
514 .env(OUTPUT_HELPER_ENV, mode)
515 .stdout(std::process::Stdio::piped())
516 .stderr(std::process::Stdio::piped())
517 .spawn()
518 .unwrap()
519 }
520
521 #[test]
522 fn wait_with_limits_captures_output() {
523 let child = spawn_output_helper("stdout-small");
524
525 let output = super::wait_with_limits(child, 1024, std::time::Duration::from_secs(5), false);
526 let stdout = String::from_utf8_lossy(&output.stdout);
527 assert!(
528 stdout.contains("hello"),
529 "expected 'hello' in output: {stdout}"
530 );
531 assert!(output.status.success());
532 }
533
534 #[test]
535 fn wait_with_limits_truncates_large_output() {
536 let child = spawn_output_helper("stdout-forever");
537
538 let output =
539 super::wait_with_limits(child, 1024, std::time::Duration::from_secs(10), false);
540 let stdout = String::from_utf8_lossy(&output.stdout);
541 assert!(
542 stdout.contains("[lean-ctx: output truncated"),
543 "expected truncation notice, got len={}: ...{}",
544 stdout.len(),
545 &stdout[stdout.len().saturating_sub(80)..]
546 );
547 }
548
549 #[test]
550 fn synthetic_failure_status_is_a_failure_without_spawning_anything() {
551 let status = super::synthetic_failure_status();
552 assert!(!status.success());
553 #[cfg(unix)]
554 {
555 use std::os::unix::process::ExitStatusExt;
556 assert_eq!(status.code(), Some(1));
557 assert_eq!(status.signal(), None);
558 }
559 }
560
561 #[test]
562 fn wait_with_limits_truncates_large_stderr() {
563 let child = spawn_output_helper("stderr-forever");
564
565 let output = super::wait_with_limits(
566 child,
567 1024 * 1024,
568 std::time::Duration::from_secs(10),
569 false,
570 );
571 let stderr = String::from_utf8_lossy(&output.stderr);
572 assert!(
573 stderr.contains("[lean-ctx: stderr truncated"),
574 "expected stderr truncation notice, got len={}: ...{}",
575 stderr.len(),
576 &stderr[stderr.len().saturating_sub(80)..]
577 );
578 }
579
580 #[test]
581 fn wait_with_limits_kills_promptly_on_truncation() {
582 let child = spawn_output_helper("stdout-forever");
583
584 let start = std::time::Instant::now();
585 let output =
586 super::wait_with_limits(child, 4096, std::time::Duration::from_secs(20), false);
587 let elapsed = start.elapsed();
588
589 assert!(
590 elapsed < std::time::Duration::from_secs(3),
591 "truncation should kill promptly, took {elapsed:?} (timeout was 20s)"
592 );
593 let stdout = String::from_utf8_lossy(&output.stdout);
594 assert!(stdout.contains("[lean-ctx: output truncated"));
595 }
596
597 #[test]
598 fn wait_with_limits_timeout_kills_process() {
599 let child = spawn_output_helper("sleep");
600
601 let start = std::time::Instant::now();
602 let output =
603 super::wait_with_limits(child, 1024, std::time::Duration::from_millis(200), false);
604 let elapsed = start.elapsed();
605
606 assert!(
607 elapsed < std::time::Duration::from_secs(3),
608 "timeout should kill quickly, took {elapsed:?}"
609 );
610 let stdout = String::from_utf8_lossy(&output.stdout);
611 assert!(stdout.contains("[lean-ctx: output truncated"));
612 }
613
614 #[cfg(unix)]
620 #[test]
621 fn wait_with_limits_group_kill_reaps_grandchildren() {
622 use std::os::unix::process::CommandExt as _;
623 let mut cmd = std::process::Command::new("sh");
627 cmd.args(["-c", "sleep 30 & sleep 30"])
628 .stdin(std::process::Stdio::null())
629 .stdout(std::process::Stdio::piped())
630 .stderr(std::process::Stdio::piped());
631 cmd.process_group(0);
632 let child = cmd.spawn().unwrap();
633 let pgid = child.id() as libc::pid_t;
634
635 let start = std::time::Instant::now();
636 let _ = super::wait_with_limits(child, 1024, std::time::Duration::from_millis(200), true);
637 let elapsed = start.elapsed();
638
639 assert!(
640 elapsed < std::time::Duration::from_secs(5),
641 "group kill must unblock the reader threads, took {elapsed:?}"
642 );
643 let mut group_gone = false;
646 for _ in 0..50 {
647 if unsafe { libc::killpg(pgid, 0) } == -1 {
649 group_gone = true;
650 break;
651 }
652 std::thread::sleep(std::time::Duration::from_millis(20));
653 }
654 assert!(group_gone, "process group {pgid} must be fully reaped");
655 }
656
657 #[cfg(unix)]
658 fn alive(pid: u32) -> bool {
659 crate::ipc::process::is_alive(pid)
660 }
661
662 #[cfg(unix)]
666 fn guardian() {
667 use std::os::unix::process::CommandExt as _;
668 use std::process::{Command, Stdio};
669 let piped = |script: &str| {
670 let mut command = Command::new("sh");
671 command
672 .args(["-c", script])
673 .stdin(Stdio::null())
674 .stdout(Stdio::piped())
675 .stderr(Stdio::piped());
676 command
677 };
678 let mut sentinel = Command::new("sleep")
679 .arg("60")
680 .stdin(Stdio::null())
681 .stdout(Stdio::null())
682 .stderr(Stdio::null())
683 .spawn()
684 .unwrap();
685 let own = unsafe { libc::getpgrp() };
687 assert_eq!(own, std::process::id() as libc::pid_t, "guardian leads");
688 struct EndOwnGroup(libc::pid_t);
692 impl Drop for EndOwnGroup {
693 fn drop(&mut self) {
694 use std::io::Write as _;
695 let _ = std::io::stdout().flush();
696 unsafe { libc::killpg(self.0, libc::SIGKILL) };
698 }
699 }
700 let _end = EndOwnGroup(own);
701 assert_eq!(unsafe { libc::getpgid(sentinel.id() as libc::pid_t) }, own);
703
704 let child = piped("sleep 60 & sleep 60").spawn().unwrap();
708 let start = std::time::Instant::now();
709 let captured = super::wait_with_limits_captured(
710 child,
711 1024,
712 std::time::Duration::from_millis(200),
713 true,
714 );
715 assert!(start.elapsed() < std::time::Duration::from_secs(8));
716 assert!(captured.completeness.timed_out);
717 assert!(captured.completeness.reader_incomplete);
718 assert!(
719 alive(sentinel.id()),
720 "inherited group must not be signalled"
721 );
722
723 let child = piped("sleep 60 & yes").spawn().unwrap();
725 let captured =
726 super::wait_with_limits_captured(child, 1024, std::time::Duration::from_secs(30), true);
727 assert!(captured.completeness.truncated);
728 assert!(
729 alive(sentinel.id()),
730 "inherited group must not be signalled"
731 );
732
733 let mut command = piped("sleep 60 & echo started");
737 command.process_group(0);
738 let child = command.spawn().unwrap();
739 let group = child.id() as libc::pid_t;
740 let start = std::time::Instant::now();
741 let captured =
742 super::wait_with_limits_captured(child, 1024, std::time::Duration::from_secs(30), true);
743 assert!(
744 start.elapsed() < std::time::Duration::from_secs(5),
745 "leader gone, pipe holder alive: must not wait for it"
746 );
747 assert!(!captured.completeness.timed_out);
748 assert!(captured.completeness.reader_incomplete);
749 assert!(String::from_utf8_lossy(&captured.output.stdout).contains("started"));
750 let mut group_gone = false;
751 for _ in 0..100 {
752 if unsafe { libc::killpg(group, 0) } == -1 {
754 group_gone = true;
755 break;
756 }
757 std::thread::sleep(std::time::Duration::from_millis(20));
758 }
759 assert!(group_gone, "the call's own group must be gone");
760 assert!(
761 alive(sentinel.id()),
762 "a foreign group must not be signalled"
763 );
764
765 let child = piped("echo written; echo problem >&2; sleep 60 &")
771 .spawn()
772 .unwrap();
773 let start = std::time::Instant::now();
774 let captured =
775 super::wait_with_limits_captured(child, 1024, std::time::Duration::from_secs(30), true);
776 assert!(start.elapsed() < std::time::Duration::from_secs(8));
777 assert!(captured.output.status.success());
778 assert!(captured.completeness.reader_incomplete);
779 assert!(!captured.completeness.timed_out && !captured.completeness.truncated);
780 assert_eq!(
781 String::from_utf8_lossy(&captured.output.stdout),
782 "written\n\n[lean-ctx: output not captured: a process outside this call kept it open]\n"
783 );
784 assert_eq!(captured.output.stderr, b"problem\n");
785 assert!(
786 alive(sentinel.id()),
787 "inherited group must not be signalled"
788 );
789
790 let child = piped("echo written; echo problem >&2").spawn().unwrap();
793 let captured =
794 super::wait_with_limits_captured(child, 1024, std::time::Duration::from_secs(30), true);
795 assert_eq!(captured.output.stdout, b"written\n");
796 assert_eq!(captured.output.stderr, b"problem\n");
797 assert!(captured.completeness.is_complete());
798
799 sentinel.kill().unwrap();
801 sentinel.wait().unwrap();
802 println!("GUARDIAN-COMPLETE");
803 }
804
805 #[cfg(unix)]
810 #[test]
811 fn limits_signal_only_a_group_the_call_owns() {
812 use std::os::unix::process::CommandExt as _;
813 let mut command = std::process::Command::new(std::env::current_exe().unwrap());
814 command
815 .args([OUTPUT_HELPER_TEST, "--exact", "--ignored", "--nocapture"])
816 .env(OUTPUT_HELPER_ENV, "guardian")
817 .stdin(std::process::Stdio::null())
818 .stdout(std::process::Stdio::piped())
819 .stderr(std::process::Stdio::piped());
820 command.process_group(0);
821 let child = command.spawn().unwrap();
822 let captured = super::wait_with_limits_captured(
825 child,
826 64 * 1024,
827 std::time::Duration::from_mins(1),
828 true,
829 );
830 let stdout = String::from_utf8_lossy(&captured.output.stdout);
831 let stderr = String::from_utf8_lossy(&captured.output.stderr);
832 assert!(
833 stdout.contains("GUARDIAN-COMPLETE"),
834 "guardian status {:?}\n{stdout}\n{stderr}",
835 captured.output.status
836 );
837 }
838
839 #[cfg(unix)]
843 #[test]
844 fn stdin_relay_forwards_piped_data() {
845 use std::io::Write;
846 use std::os::unix::process::CommandExt as _;
847
848 let mut cmd = std::process::Command::new("cat");
849 cmd.stdin(std::process::Stdio::piped())
850 .stdout(std::process::Stdio::piped())
851 .stderr(std::process::Stdio::piped());
852 cmd.process_group(0);
853 let mut child = cmd.spawn().expect("failed to spawn cat");
854
855 let mut child_stdin = child.stdin.take().unwrap();
856 std::thread::spawn(move || {
857 child_stdin.write_all(b"hello from pipe\n").unwrap();
858 drop(child_stdin);
859 });
860
861 let output = child.wait_with_output().expect("wait failed");
862 let stdout = String::from_utf8_lossy(&output.stdout);
863 assert!(
864 stdout.contains("hello from pipe"),
865 "#806: piped stdin must reach the child, got: {stdout}"
866 );
867 }
868
869 #[cfg(unix)]
872 #[test]
873 fn stdin_relay_no_data_does_not_hang() {
874 let start = std::time::Instant::now();
875 let mut cmd = std::process::Command::new("sh");
876 cmd.args(["-c", "echo ok"])
877 .stdin(std::process::Stdio::piped())
878 .stdout(std::process::Stdio::piped())
879 .stderr(std::process::Stdio::piped());
880 use std::os::unix::process::CommandExt as _;
881 cmd.process_group(0);
882 let mut child = cmd.spawn().unwrap();
883 drop(child.stdin.take());
885 let output = child.wait_with_output().unwrap();
886 let elapsed = start.elapsed();
887 assert!(
888 elapsed < std::time::Duration::from_secs(5),
889 "must not hang when stdin is closed immediately, took {elapsed:?}"
890 );
891 let stdout = String::from_utf8_lossy(&output.stdout);
892 assert!(stdout.contains("ok"), "command output missing: {stdout}");
893 }
894}