use std::fs::File;
use std::io::{Read, Write};
use std::os::fd::{AsRawFd, OwnedFd};
use std::os::unix::process::CommandExt;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
const LONGEST_WAIT: Duration = Duration::from_millis(50);
const DRAIN_LIMIT: usize = 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Keep {
Nothing,
All { cap: usize },
Tail(usize),
}
impl Keep {
fn stdio(self) -> Stdio {
match self {
Keep::Nothing => Stdio::null(),
Keep::All { .. } | Keep::Tail(_) => Stdio::piped(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Apart {
No,
Session,
Group,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Bounded {
pub stdout: Keep,
pub stderr: Keep,
pub apart: Apart,
pub limit: Duration,
pub retry_busy: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Stream {
Stdout,
Stderr,
}
#[derive(Debug)]
pub(crate) struct Ran {
pub status: ExitStatus,
pub stdout: Kept,
pub stderr: Kept,
pub took_input: bool,
}
#[derive(Debug)]
pub(crate) enum RunError {
Spawn(std::io::Error),
TimedOut,
TooLong { stream: Stream, cap: usize },
Wait(std::io::Error),
Pipe(std::io::Error),
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub(crate) struct Kept {
bytes: Vec<u8>,
cut: bool,
}
impl Kept {
pub(crate) fn into_bytes(self) -> Vec<u8> {
self.bytes
}
pub(crate) fn cut(&self) -> bool {
self.cut
}
pub(crate) fn text(&self) -> String {
let start = if self.cut {
self.bytes
.iter()
.position(|b| b & 0xC0 != 0x80)
.unwrap_or(self.bytes.len())
} else {
0
};
String::from_utf8_lossy(&self.bytes[start..]).into_owned()
}
fn add(&mut self, new: &[u8], keep: Keep, stream: Stream) -> Result<(), RunError> {
match keep {
Keep::Nothing => {}
Keep::All { cap } => {
if self.bytes.len() + new.len() > cap {
return Err(RunError::TooLong { stream, cap });
}
self.bytes.extend_from_slice(new);
}
Keep::Tail(n) => {
self.bytes.extend_from_slice(new);
if let Some(over) = self.bytes.len().checked_sub(n).filter(|&o| o > 0) {
self.bytes.drain(..over);
self.cut = true;
}
}
}
Ok(())
}
}
impl Bounded {
#[track_caller]
pub(crate) fn run(self, cmd: &mut Command) -> Result<Ran, RunError> {
super::about_to_wait(cmd.get_program());
self.run_with(cmd, None, None).map_err(Short::into_error)
}
#[track_caller]
pub(crate) fn run_unless(
self,
cmd: &mut Command,
unwanted: &AtomicBool,
) -> Option<Result<Ran, RunError>> {
super::about_to_wait(cmd.get_program());
match self.run_with(cmd, None, Some(unwanted)) {
Ok(ran) => Some(Ok(ran)),
Err(Short::Error(e)) => Some(Err(e)),
Err(Short::Unwanted) => None,
}
}
#[track_caller]
pub(crate) fn run_fed(self, cmd: &mut Command, input: &[u8]) -> Result<Ran, RunError> {
super::about_to_wait(cmd.get_program());
self.run_with(cmd, Some(input), None)
.map_err(Short::into_error)
}
fn run_with(
self,
cmd: &mut Command,
input: Option<&[u8]>,
unwanted: Option<&AtomicBool>,
) -> Result<Ran, Short> {
let deadline = Instant::now() + self.limit;
cmd.stdin(if input.is_some() {
Stdio::piped()
} else {
Stdio::null()
})
.stdout(self.stdout.stdio())
.stderr(self.stderr.stdio());
match self.apart {
Apart::No => {}
Apart::Session => unsafe {
cmd.pre_exec(|| {
libc::setsid();
Ok(())
});
},
Apart::Group => {
cmd.process_group(0);
}
}
let started = if self.retry_busy {
super::retry_while_busy(
|| cmd.spawn(),
|r| r.as_ref().is_err_and(super::text_file_busy) && Instant::now() < deadline,
)
} else {
cmd.spawn()
};
let mut child = started.map_err(RunError::Spawn)?;
let stdout = Pipe::new(
child.stdout.take().map(OwnedFd::from),
self.stdout,
Stream::Stdout,
);
let stderr = Pipe::new(
child.stderr.take().map(OwnedFd::from),
self.stderr,
Stream::Stderr,
);
let feed = Feed::new(
child.stdin.take().map(OwnedFd::from),
input.unwrap_or_default(),
);
let (mut pipes, mut feed) = match (stdout, stderr, feed) {
(Ok(stdout), Ok(stderr), Ok(feed)) => ([stdout, stderr], feed),
(Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => {
stop(child, self.apart);
return Err(RunError::Pipe(e).into());
}
};
let mut quiet = 0u32;
loop {
let mut heard = feed.write();
for pipe in &mut pipes {
match pipe.drain() {
Ok(took) => heard |= took,
Err(refused) => {
stop(child, self.apart);
return Err(refused.into());
}
}
}
match exited(&mut child, self.apart) {
Ok(Some(status)) => {
for pipe in &mut pipes {
pipe.finish()?;
}
let [stdout, stderr] = pipes.map(|pipe| pipe.kept);
return Ok(Ran {
status,
stdout,
stderr,
took_input: feed.left.is_empty(),
});
}
Ok(None) => {
if unwanted.is_some_and(|u| u.load(Ordering::Relaxed)) {
stop(child, self.apart);
return Err(Short::Unwanted);
}
let now = Instant::now();
if now >= deadline {
stop(child, self.apart);
return Err(RunError::TimedOut.into());
}
quiet = if heard { 0 } else { quiet.saturating_add(1) };
wait_for_pipes(&pipes, &feed, pause(quiet).min(deadline - now));
}
Err(e) => {
stop(child, self.apart);
return Err(RunError::Wait(e).into());
}
}
}
}
}
enum Short {
Error(RunError),
Unwanted,
}
impl Short {
fn into_error(self) -> RunError {
match self {
Short::Error(e) => e,
Short::Unwanted => unreachable!("only a run handed a flag is stopped by it"),
}
}
}
impl From<RunError> for Short {
fn from(e: RunError) -> Self {
Short::Error(e)
}
}
fn pause(quiet: u32) -> Duration {
Duration::from_millis(1u64 << quiet.min(6)).min(LONGEST_WAIT)
}
struct Pipe {
file: Option<File>,
keep: Keep,
stream: Stream,
kept: Kept,
}
impl Pipe {
fn new(fd: Option<OwnedFd>, keep: Keep, stream: Stream) -> std::io::Result<Self> {
if let Some(fd) = &fd
&& !super::set_nonblocking_on(fd.as_raw_fd())
{
return Err(std::io::Error::last_os_error());
}
Ok(Self {
file: fd.map(File::from),
keep,
stream,
kept: Kept::default(),
})
}
fn drain(&mut self) -> Result<bool, RunError> {
let Some(file) = self.file.as_mut() else {
return Ok(false);
};
let mut chunk = [0u8; 8192];
let mut taken = 0;
let mut ended = false;
while taken < DRAIN_LIMIT {
match file.read(&mut chunk) {
Ok(0) => {
ended = true;
break;
}
Ok(n) => {
taken += n;
self.kept.add(&chunk[..n], self.keep, self.stream)?;
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
Err(_) => {
ended = true;
break;
}
}
}
if ended {
self.file = None;
}
Ok(taken > 0)
}
fn finish(&mut self) -> Result<(), RunError> {
self.drain().map(|_| ())
}
}
struct Feed<'a> {
file: Option<File>,
left: &'a [u8],
}
impl<'a> Feed<'a> {
fn new(fd: Option<OwnedFd>, input: &'a [u8]) -> std::io::Result<Self> {
if let Some(fd) = &fd
&& !super::set_nonblocking_on(fd.as_raw_fd())
{
return Err(std::io::Error::last_os_error());
}
Ok(Self {
file: fd.map(File::from).filter(|_| !input.is_empty()),
left: input,
})
}
fn write(&mut self) -> bool {
let Some(file) = self.file.as_mut() else {
return false;
};
let mut written = 0;
let mut done = false;
while written < DRAIN_LIMIT {
match file.write(self.left) {
Ok(n) if n > 0 => {
written += n;
self.left = &self.left[n..];
if self.left.is_empty() {
done = true;
break;
}
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
Ok(_) | Err(_) => {
done = true;
break;
}
}
}
if done {
self.file = None;
}
written > 0
}
}
fn wait_for_pipes(pipes: &[Pipe], feed: &Feed, wait: Duration) {
let reads = pipes
.iter()
.filter_map(|pipe| pipe.file.as_ref())
.map(|file| (file, libc::POLLIN));
let writes = feed.file.as_ref().map(|file| (file, libc::POLLOUT));
let mut ready: Vec<libc::pollfd> = reads
.chain(writes)
.map(|(file, events)| libc::pollfd {
fd: file.as_raw_fd(),
events,
revents: 0,
})
.collect();
if ready.is_empty() {
std::thread::sleep(wait);
return;
}
let ms = libc::c_int::try_from(wait.as_millis()).unwrap_or(libc::c_int::MAX);
unsafe { libc::poll(ready.as_mut_ptr(), ready.len() as libc::nfds_t, ms) };
}
fn exited(child: &mut Child, apart: Apart) -> std::io::Result<Option<ExitStatus>> {
if apart != Apart::Session {
return child.try_wait();
}
let Ok(pid) = i32::try_from(child.id()) else {
return child.try_wait();
};
if !exited_unreaped(pid)? {
return Ok(None);
}
unsafe { libc::kill(-pid, libc::SIGKILL) };
child.wait().map(Some)
}
fn exited_unreaped(pid: i32) -> std::io::Result<bool> {
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let asked = unsafe {
libc::waitid(
libc::P_PID,
pid as libc::id_t,
&mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if asked != 0 {
let err = std::io::Error::last_os_error();
return if err.kind() == std::io::ErrorKind::Interrupted {
Ok(false)
} else {
Err(err)
};
}
#[cfg(target_vendor = "apple")]
let who = info.si_pid;
#[cfg(not(target_vendor = "apple"))]
let who = unsafe { info.si_pid() };
Ok(who != 0)
}
fn stop(mut child: Child, apart: Apart) {
if apart != Apart::No
&& let Ok(pid) = i32::try_from(child.id())
{
unsafe { libc::kill(-pid, libc::SIGKILL) };
}
let _ = child.kill();
std::thread::spawn(move || {
let _ = child.wait();
});
}
#[cfg(test)]
mod tests {
use super::*;
fn sh(script: &str) -> Command {
let mut cmd = Command::new("/bin/sh");
cmd.args(["-c", script]);
cmd
}
fn bounded(stdout: Keep, stderr: Keep, limit: Duration) -> Bounded {
Bounded {
stdout,
stderr,
apart: Apart::No,
limit,
retry_busy: false,
}
}
#[cfg(target_os = "linux")]
fn gone(pid: i32) -> bool {
let signalled = unsafe { libc::kill(pid, 0) };
signalled != 0
|| std::fs::read_to_string(format!("/proc/{pid}/stat"))
.ok()
.and_then(|stat| {
let after = stat.rsplit_once(')')?.1;
after.split_whitespace().next().map(|state| state == "Z")
})
.unwrap_or(true)
}
#[cfg(target_os = "linux")]
fn wait_gone(pid: i32) -> bool {
let until = Instant::now() + Duration::from_secs(5);
while Instant::now() < until {
if gone(pid) {
return true;
}
std::thread::sleep(Duration::from_millis(10));
}
gone(pid)
}
#[test]
fn a_program_is_run_to_its_exit_with_what_it_wrote() {
let ran = bounded(
Keep::All { cap: 1024 },
Keep::All { cap: 1024 },
Duration::from_secs(5),
)
.run(&mut sh("echo out; echo err >&2; exit 3"))
.unwrap();
assert_eq!(ran.status.code(), Some(3));
assert_eq!(ran.stdout.text(), "out\n");
assert_eq!(ran.stderr.text(), "err\n");
}
#[cfg(target_os = "linux")]
#[test]
fn its_input_and_an_unkept_stream_are_null() {
let mut cmd =
sh("i=$(readlink /proc/$$/fd/0); o=$(readlink /proc/$$/fd/1); echo \"$i $o\" >&2");
cmd.stdin(Stdio::piped()).stdout(Stdio::piped());
let ran = bounded(
Keep::Nothing,
Keep::All { cap: 1024 },
Duration::from_secs(5),
)
.run(&mut cmd)
.unwrap();
assert_eq!(ran.stderr.text(), "/dev/null /dev/null\n");
assert!(ran.stdout.text().is_empty());
}
#[test]
fn a_program_that_cannot_start_is_reported_as_not_started() {
let run = bounded(Keep::Nothing, Keep::Nothing, Duration::from_secs(5))
.run(&mut Command::new("/nonexistent/croft-test-program"));
assert!(matches!(run, Err(RunError::Spawn(_))), "{run:?}");
}
#[test]
fn a_stream_kept_whole_is_refused_past_its_cap() {
let started = Instant::now();
let run = bounded(
Keep::All { cap: 1000 },
Keep::Nothing,
Duration::from_secs(20),
)
.run(&mut sh("exec yes x"));
assert!(
matches!(
run,
Err(RunError::TooLong {
stream: Stream::Stdout,
cap: 1000
})
),
"{run:?}"
);
assert!(started.elapsed() < Duration::from_secs(10));
}
#[test]
fn a_stream_exactly_at_its_cap_is_kept() {
let ran = bounded(Keep::All { cap: 6 }, Keep::Nothing, Duration::from_secs(5))
.run(&mut sh("printf 'abcdef'"))
.unwrap();
assert_eq!(ran.stdout.text(), "abcdef");
}
#[test]
fn a_tail_keeps_the_end_of_a_fast_flood() {
let ran = bounded(Keep::Tail(64), Keep::Nothing, Duration::from_secs(3))
.run(&mut sh("head -c 8000000 /dev/zero | tr '\\0' x; echo done"))
.unwrap();
assert!(ran.stdout.cut());
assert_eq!(ran.stdout.text().len(), 64);
assert!(
ran.stdout.text().ends_with("xdone\n"),
"{}",
ran.stdout.text()
);
}
#[test]
fn a_helper_holding_a_stream_does_not_hold_the_run() {
let dir = tempfile::tempdir().unwrap();
let pid = dir.path().join("helper.pid");
let started = Instant::now();
let ran = bounded(
Keep::All { cap: 1024 },
Keep::Nothing,
Duration::from_secs(20),
)
.run(&mut sh(&format!(
"sleep 30 & echo $! > '{}'; echo hi",
pid.display()
)))
.unwrap();
let took = started.elapsed();
let helper = std::fs::read_to_string(&pid).ok();
if let Some(helper) = helper.and_then(|h| h.trim().parse::<i32>().ok()) {
unsafe { libc::kill(helper, libc::SIGKILL) };
}
assert_eq!(ran.stdout.text(), "hi\n");
assert!(took < Duration::from_secs(10), "took {took:?}");
}
#[test]
fn a_program_that_never_stops_writing_is_killed_at_its_limit() {
let started = Instant::now();
let run = bounded(Keep::Tail(64), Keep::Nothing, Duration::from_millis(300))
.run(&mut sh("exec yes x"));
assert!(matches!(run, Err(RunError::TimedOut)), "{run:?}");
assert!(started.elapsed() < Duration::from_secs(10));
}
#[cfg(target_os = "linux")]
#[test]
fn an_unwanted_run_is_killed_with_what_it_started() {
let dir = tempfile::tempdir().unwrap();
let pids = dir.path().join("pids");
let unwanted = std::sync::Arc::new(AtomicBool::new(false));
let flag = unwanted.clone();
let pids_at = pids.clone();
let setter = std::thread::spawn(move || {
let until = Instant::now() + Duration::from_secs(10);
while !pids_at.exists() && Instant::now() < until {
std::thread::sleep(Duration::from_millis(5));
}
flag.store(true, Ordering::Relaxed);
});
let started = Instant::now();
let run = Bounded {
stdout: Keep::Nothing,
stderr: Keep::Nothing,
apart: Apart::Session,
limit: Duration::from_secs(60),
retry_busy: false,
}
.run_unless(
&mut sh(&format!(
"sleep 30 & echo $$ $! > '{}.tmp' && mv '{0}.tmp' '{0}'; wait",
pids.display()
)),
&unwanted,
);
setter.join().unwrap();
assert!(run.is_none(), "{run:?}");
assert!(
started.elapsed() < Duration::from_secs(20),
"stopped at once"
);
let pids = std::fs::read_to_string(&pids).unwrap();
let pids: Vec<i32> = pids
.split_whitespace()
.map(|p| p.parse().unwrap())
.collect();
let [shell, helper] = pids[..] else {
panic!("{pids:?}");
};
assert!(wait_gone(shell), "the program is killed");
assert!(wait_gone(helper), "and what it started with it");
}
#[test]
fn a_wanted_run_goes_to_its_exit() {
let wanted = AtomicBool::new(false);
let ran = bounded(
Keep::All { cap: 64 },
Keep::Nothing,
Duration::from_secs(10),
)
.run_unless(&mut sh("echo done"), &wanted)
.expect("still wanted")
.expect("ran");
assert!(ran.status.success());
assert_eq!(ran.stdout.into_bytes(), b"done\n");
}
#[test]
fn the_wait_between_checks_starts_short_and_grows_to_the_longest() {
assert_eq!(pause(0), Duration::from_millis(1));
assert_eq!(pause(1), Duration::from_millis(2));
assert_eq!(pause(5), Duration::from_millis(32));
assert_eq!(pause(6), LONGEST_WAIT);
assert_eq!(pause(u32::MAX), LONGEST_WAIT);
}
#[cfg(target_os = "linux")]
#[test]
fn a_detached_program_runs_apart_and_is_killed_with_what_it_started() {
let dir = tempfile::tempdir().unwrap();
let pids = dir.path().join("pids");
let run = Bounded {
stdout: Keep::Nothing,
stderr: Keep::Nothing,
apart: Apart::Session,
limit: Duration::from_millis(500),
retry_busy: false,
}
.run(&mut sh(&format!(
"sleep 30 & echo $$ $! $(cut -d' ' -f6 /proc/$$/stat) > '{}'; wait",
pids.display()
)));
assert!(matches!(run, Err(RunError::TimedOut)), "{run:?}");
let pids = std::fs::read_to_string(&pids).unwrap();
let pids: Vec<i32> = pids
.split_whitespace()
.map(|p| p.parse().unwrap())
.collect();
let [shell, helper, session] = pids[..] else {
panic!("{pids:?}");
};
assert_eq!(session, shell, "it leads a session of its own");
assert!(wait_gone(shell), "the program is killed");
assert!(wait_gone(helper), "and what it started with it");
}
#[cfg(target_os = "linux")]
#[test]
fn what_a_detached_program_leaves_running_is_killed_at_its_exit() {
let dir = tempfile::tempdir().unwrap();
let pid = dir.path().join("helper.pid");
let started = Instant::now();
let ran = Bounded {
stdout: Keep::All { cap: 64 },
stderr: Keep::Nothing,
apart: Apart::Session,
limit: Duration::from_secs(20),
retry_busy: false,
}
.run(&mut sh(&format!(
"sleep 30 & echo $! > '{}'; echo answer",
pid.display()
)))
.unwrap();
assert!(
started.elapsed() < Duration::from_secs(10),
"answered at its exit"
);
assert_eq!(ran.stdout.text(), "answer\n");
assert!(ran.status.success());
let helper: i32 = std::fs::read_to_string(&pid)
.unwrap()
.trim()
.parse()
.unwrap();
assert!(wait_gone(helper), "the job it left running is killed");
}
#[cfg(target_os = "linux")]
#[test]
fn a_program_in_a_group_of_its_own_is_killed_with_what_it_started() {
let dir = tempfile::tempdir().unwrap();
let pids = dir.path().join("pids");
let run = Bounded {
stdout: Keep::Nothing,
stderr: Keep::Nothing,
apart: Apart::Group,
limit: Duration::from_millis(500),
retry_busy: false,
}
.run(&mut sh(&format!(
"sleep 30 & echo $$ $! $(cut -d' ' -f5,6 /proc/$$/stat) > '{}'; wait",
pids.display()
)));
assert!(matches!(run, Err(RunError::TimedOut)), "{run:?}");
let pids = std::fs::read_to_string(&pids).unwrap();
let pids: Vec<i32> = pids
.split_whitespace()
.map(|p| p.parse().unwrap())
.collect();
let [shell, helper, group, session] = pids[..] else {
panic!("{pids:?}");
};
assert_eq!(group, shell, "it leads a group of its own");
assert_eq!(session, unsafe { libc::getsid(0) }, "in croft's session");
assert!(wait_gone(shell), "the program is killed");
assert!(wait_gone(helper), "and what it started with it");
}
#[cfg(target_os = "linux")]
#[test]
fn what_a_program_in_a_group_of_its_own_leaves_after_its_exit_is_kept() {
let dir = tempfile::tempdir().unwrap();
let pid = dir.path().join("helper.pid");
let ran = Bounded {
stdout: Keep::Nothing,
stderr: Keep::Nothing,
apart: Apart::Group,
limit: Duration::from_secs(20),
retry_busy: false,
}
.run(&mut sh(&format!(
"sleep 30 </dev/null >/dev/null 2>&1 & echo $! > '{}'",
pid.display()
)))
.unwrap();
assert!(ran.status.success());
let helper: i32 = std::fs::read_to_string(&pid)
.unwrap()
.trim()
.parse()
.unwrap();
std::thread::sleep(Duration::from_millis(200));
let kept = !gone(helper);
unsafe { libc::kill(helper, libc::SIGKILL) };
assert!(kept, "what it left running is kept");
}
#[cfg(target_os = "linux")]
#[test]
fn an_attached_program_stays_in_crofts_session() {
let ran = bounded(Keep::All { cap: 64 }, Keep::Nothing, Duration::from_secs(5))
.run(&mut sh("cut -d' ' -f6 /proc/$$/stat"))
.unwrap();
let ours = unsafe { libc::getsid(0) };
assert_eq!(ran.stdout.text().trim(), ours.to_string());
}
#[cfg(target_os = "linux")]
#[test]
fn a_stream_that_cannot_read_without_waiting_is_refused() {
use std::os::unix::fs::OpenOptionsExt;
let path_only = std::fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_PATH)
.open("/")
.unwrap();
let refused = Pipe::new(
Some(OwnedFd::from(path_only)),
Keep::Tail(64),
Stream::Stdout,
);
assert!(refused.is_err());
assert!(Pipe::new(None, Keep::Nothing, Stream::Stdout).is_ok());
}
#[test]
fn a_cut_tail_starts_at_a_whole_character() {
let mut kept = Kept::default();
let tail = Keep::Tail(64);
kept.add("é".repeat(32).as_bytes(), tail, Stream::Stderr)
.unwrap();
kept.add(b"z", tail, Stream::Stderr).unwrap();
let text = kept.text();
assert!(kept.cut());
assert!(text.starts_with('é'), "{text}");
assert!(text.ends_with("éz"));
assert!(!text.contains('\u{fffd}'));
}
#[test]
fn fed_input_larger_than_a_pipe_passes_through_whole() {
let input: Vec<u8> = (0..4 * 1024 * 1024).map(|i| (i % 251) as u8).collect();
let ran = bounded(
Keep::All {
cap: 8 * 1024 * 1024,
},
Keep::Nothing,
Duration::from_secs(10),
)
.run_fed(&mut sh("exec cat"), &input)
.unwrap();
assert!(ran.status.success());
assert!(ran.took_input);
assert!(ran.stdout.into_bytes() == input);
}
#[test]
fn empty_fed_input_ends_at_once() {
let ran = bounded(
Keep::All { cap: 1024 },
Keep::Nothing,
Duration::from_secs(5),
)
.run_fed(&mut sh("cat; echo end"), b"")
.unwrap();
assert!(ran.status.success());
assert!(ran.took_input, "there was nothing to take");
assert_eq!(ran.stdout.text(), "end\n");
}
#[test]
fn a_program_that_reads_none_of_its_input_still_answers() {
let input = vec![b'x'; 4 * 1024 * 1024];
let ran = bounded(
Keep::All { cap: 1024 },
Keep::Nothing,
Duration::from_secs(5),
)
.run_fed(&mut sh("echo done"), &input)
.unwrap();
assert!(ran.status.success());
assert!(!ran.took_input, "it never read its input");
assert_eq!(ran.stdout.text(), "done\n");
}
#[test]
fn a_program_that_stops_reading_its_input_is_killed_at_the_limit() {
let input = vec![b'x'; 4 * 1024 * 1024];
let started = Instant::now();
let run = bounded(Keep::Nothing, Keep::Nothing, Duration::from_millis(300))
.run_fed(&mut sh("exec sleep 30"), &input);
assert!(matches!(run, Err(RunError::TimedOut)), "{run:?}");
assert!(started.elapsed() < Duration::from_secs(3));
}
}