mod common;
use oscall::process;
#[test]
fn ids() {
#[cfg(not(target_family = "wasm"))]
{
assert_eq!(process::id(), std::process::id());
assert_ne!(process::parent_id(), 0);
assert_ne!(process::parent_id(), process::id());
}
#[cfg(unix)]
assert_eq!(process::parent_id(), std::os::unix::process::parent_id());
#[cfg(target_family = "wasm")]
{
assert_eq!(process::id(), 0);
assert_eq!(process::parent_id(), 0);
}
}
#[test]
#[cfg(all(feature = "alloc", target_family = "wasm"))]
fn spawn_unsupported() {
use oscall::process::{Command, Stdio};
let error = Command::new("/bin/sh")
.args(&["-c", "exit 0"])
.stdin(Stdio::Null)
.spawn()
.unwrap_err();
assert_eq!(error.kind(), oscall::ErrorKind::Unsupported);
}
#[test]
#[cfg(target_family = "wasm")]
fn processes_unsupported() {
use oscall::ErrorKind;
let mut buf = [0u8; 64];
let error = process::find_program("sh", "/bin", &mut buf).unwrap_err();
assert_eq!(error.kind(), ErrorKind::Unsupported);
#[cfg(feature = "alloc")]
assert_eq!(
process::find_program_vec("sh", "/bin").unwrap_err().kind(),
ErrorKind::Unsupported
);
assert_eq!(
process::exists(1).unwrap_err().kind(),
ErrorKind::Unsupported
);
assert_eq!(process::kill(1).unwrap_err().kind(), ErrorKind::Unsupported);
assert_eq!(
process::resource_usage().unwrap_err().kind(),
ErrorKind::Unsupported
);
assert_eq!(
process::exists(0).unwrap_err().kind(),
ErrorKind::InvalidInput
);
}
#[test]
#[cfg(not(target_family = "wasm"))]
fn find_program_errors() {
use oscall::ErrorKind;
let mut buf = [0u8; 256];
let dir = common::tmp_dir("process_find_program_errors");
let dir = dir.to_str().unwrap();
for (name, path) in [("a\0", dir), ("a", "x\0y")] {
let error = process::find_program(name, path, &mut buf).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
for (name, path) in [
("", dir),
("missing", dir),
("missing", ""),
("missing", ";:"),
] {
let error = process::find_program(name, path, &mut buf).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
}
let error = process::find_program("missing", dir, &mut buf[..4]).unwrap_err();
assert_eq!(error.kind(), ErrorKind::BufferTooSmall, "{error:?}");
}
#[test]
#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
fn find_program() {
use oscall::ErrorKind;
use std::os::unix::fs::PermissionsExt;
let dir = common::tmp_dir("process_find_program");
let file = |name: &str, mode: u32| {
let path = dir.join(name);
std::fs::write(&path, "#!/bin/sh\nexit 0\n").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
};
for sub in ["a", "b", "a/folder", "b/folder"] {
std::fs::create_dir(dir.join(sub)).unwrap();
}
file("a/both", 0o755);
file("b/both", 0o755);
file("a/second", 0o644);
file("b/second", 0o700);
file("b/data", 0o644);
std::os::unix::fs::symlink("both", dir.join("b/link")).unwrap();
std::os::unix::fs::symlink("nowhere", dir.join("a/link")).unwrap();
let dir = dir.to_str().unwrap();
let path = format!("{dir}/missing::{dir}/a:{dir}/b/:");
let find = |name: &str| {
let mut buf = [0u8; 512];
let found = process::find_program(name, path.as_str(), &mut buf)
.map(|len| String::from_utf8(buf[..len].to_vec()).unwrap());
#[cfg(feature = "alloc")]
assert_eq!(
process::find_program_vec(name, path.as_str())
.map(|found| String::from_utf8(found).unwrap()),
found
);
found
};
assert_eq!(find("both").unwrap(), format!("{dir}/a/both"));
assert_eq!(find("second").unwrap(), format!("{dir}/b/second"));
assert_eq!(find("link").unwrap(), format!("{dir}/b/link"));
for name in ["data", "folder", "missing", ".", ".."] {
assert_eq!(
find(name).unwrap_err().kind(),
ErrorKind::NotFound,
"{name}"
);
}
let both = format!("{dir}/b/both");
assert_eq!(find(&both).unwrap(), both);
assert_eq!(find("a/both").unwrap_err().kind(), ErrorKind::NotFound);
let data = format!("{dir}/b/data");
assert_eq!(find(&data).unwrap_err().kind(), ErrorKind::NotFound);
let mut buf = [0u8; 512];
let path = format!("{dir}/a");
let len = dir.len() + "/a/both".len();
assert_eq!(
process::find_program("both", path.as_str(), &mut buf[..len]),
Ok(len)
);
assert_eq!(
process::find_program("both", path.as_str(), &mut buf[..len - 1])
.unwrap_err()
.kind(),
ErrorKind::BufferTooSmall
);
}
#[test]
#[cfg(windows)]
fn find_program() {
use oscall::ErrorKind;
let root = std::env::var("SystemRoot").unwrap();
let dir = common::tmp_dir("process_find_program");
std::fs::write(dir.join("data"), "x").unwrap();
std::fs::write(dir.join("tool.exe"), "x").unwrap();
std::fs::write(dir.join("script.cmd"), "x").unwrap();
std::fs::create_dir(dir.join("folder.exe")).unwrap();
let dir = dir.to_str().unwrap();
let path = format!("{dir}\\missing;;\"{dir}\";{root}\\System32\\;{root}");
let find = |name: &str| {
let mut buf = [0u8; 512];
let found = process::find_program(name, path.as_str(), &mut buf)
.map(|len| String::from_utf8(buf[..len].to_vec()).unwrap());
#[cfg(feature = "alloc")]
assert_eq!(
process::find_program_vec(name, path.as_str())
.map(|found| String::from_utf8(found).unwrap()),
found
);
found
};
assert_eq!(find("cmd").unwrap(), format!("{root}\\System32\\cmd.exe"));
assert_eq!(
find("cmd.exe").unwrap(),
format!("{root}\\System32\\cmd.exe")
);
assert_eq!(find("tool").unwrap(), format!("{dir}\\tool.exe"));
assert_eq!(find("script.cmd").unwrap(), format!("{dir}\\script.cmd"));
for name in [
"data",
"script",
"folder",
"folder.exe",
"cmd.com",
"missing",
] {
assert_eq!(
find(name).unwrap_err().kind(),
ErrorKind::NotFound,
"{name}"
);
}
let cmd = format!("{root}\\System32\\cmd.exe");
assert_eq!(find(&cmd).unwrap(), cmd);
let bare = format!("{root}\\System32\\cmd");
assert_eq!(find(&bare).unwrap_err().kind(), ErrorKind::NotFound);
assert_eq!(
find("System32\\cmd.exe").unwrap_err().kind(),
ErrorKind::NotFound
);
assert_eq!(find("C:cmd.exe").unwrap_err().kind(), ErrorKind::NotFound);
}
#[test]
#[cfg(not(target_family = "wasm"))]
fn pid_errors() {
use oscall::ErrorKind;
assert_eq!(process::exists(process::id()), Ok(true));
for pid in [0, u32::MAX, 1 << 31] {
let error = process::exists(pid).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let error = process::kill(pid).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
}
#[test]
#[cfg(not(target_family = "wasm"))]
fn resource_usage() {
use oscall::time::Clock;
use std::time::Duration;
const BLOCK: usize = 48 << 20;
let total = |usage: process::ResourceUsage| usage.user_time() + usage.system_time();
let before = process::resource_usage().unwrap();
assert!(before.max_resident_memory() > 0);
let mut block = vec![0u8; BLOCK];
for at in (0..BLOCK).step_by(512) {
block[at] = at as u8;
}
let start = Clock::ProcessCpu.now().unwrap();
let mut sum = 0u64;
while Clock::ProcessCpu.now().unwrap() - start < Duration::from_millis(100) {
for byte in block.iter().step_by(4096) {
sum = sum.wrapping_mul(31).wrapping_add(u64::from(*byte));
}
}
std::hint::black_box(sum);
let after = process::resource_usage().unwrap();
let clock = Clock::ProcessCpu.now().unwrap();
drop(block);
let peak = after.max_resident_memory();
assert!(peak >= BLOCK as u64 / 2, "{peak}");
assert!(peak >= before.max_resident_memory(), "{before:?} {after:?}");
assert!(peak < 1 << 44, "{peak}");
let spent = total(after).saturating_sub(total(before));
assert!(spent >= Duration::from_millis(50), "{before:?} {after:?}");
assert!(
total(after) <= clock + Duration::from_millis(100),
"{after:?} {clock:?}"
);
}
#[test]
#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
fn limits() {
use oscall::ErrorKind;
use oscall::process::unix::{self, Limit, Resource};
for resource in [
Resource::OpenFiles,
Resource::Stack,
Resource::CoreSize,
Resource::FileSize,
Resource::CpuTime,
Resource::AddressSpace,
Resource::Data,
Resource::LockedMemory,
Resource::Processes,
] {
let limit = unix::limit(resource).unwrap();
if let (Some(soft), Some(hard)) = (limit.soft, limit.hard) {
assert!(soft <= hard, "{resource:?}: {limit:?}");
}
let adjusted = cfg!(target_os = "macos") && resource == Resource::Processes;
if !adjusted && (resource != Resource::OpenFiles || limit.soft.is_some()) {
unix::set_limit(resource, limit).unwrap();
assert_eq!(unix::limit(resource), Ok(limit), "{resource:?}");
}
}
let files = unix::limit(Resource::OpenFiles).unwrap();
assert!(files.soft.is_none_or(|soft| soft > 3), "{files:?}");
let core = unix::limit(Resource::CoreSize).unwrap();
let none = Limit {
soft: Some(0),
hard: core.hard,
};
unix::set_limit(Resource::CoreSize, none).unwrap();
let seen = unix::limit(Resource::CoreSize);
let child = std::process::Command::new("/bin/sh")
.args(["-c", "ulimit -c"])
.output();
let above = core.hard.map(|hard| {
unix::set_limit(
Resource::CoreSize,
Limit {
soft: Some(hard + 1),
hard: Some(hard),
},
)
});
let huge = unix::set_limit(
Resource::CoreSize,
Limit {
soft: Some(u64::MAX),
hard: core.hard,
},
);
unix::set_limit(Resource::CoreSize, core).unwrap();
assert_eq!(unix::limit(Resource::CoreSize), Ok(core));
assert_eq!(seen, Ok(none));
assert_eq!(String::from_utf8_lossy(&child.unwrap().stdout).trim(), "0");
if let Some(above) = above {
let error = above.unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
let error = huge.unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
#[test]
#[cfg(not(target_family = "wasm"))]
fn helper_child_process() {
let Some(mode) = std::env::var_os("OSCALL_TEST_HELPER") else {
return;
};
let mode = mode.into_string().unwrap();
if let Some(code) = mode.strip_prefix("exit:") {
process::exit(code.parse().unwrap());
} else if mode == "abort" {
process::abort();
} else if let Some(file) = mode.strip_prefix("ids:") {
let ids = format!("{} {}", process::id(), process::parent_id());
std::fs::write(file, ids).unwrap();
process::exit(0);
} else if let Some(file) = mode.strip_prefix("args:") {
let mut out = Vec::new();
for arg in std::env::args_os().skip_while(|arg| arg != "--").skip(1) {
out.extend_from_slice(arg.as_encoded_bytes());
out.push(0);
}
std::fs::write(file, out).unwrap();
process::exit(0);
}
panic!("unknown helper mode {mode}");
}
#[cfg(all(feature = "alloc", not(target_family = "wasm")))]
mod children {
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use oscall::process::{Child, Command, ExitStatus, Stdio};
use oscall::{AsHandle, Error, ErrorKind, OwnedHandle, io};
use super::common::{handle_of, tmp_dir};
fn bytes(path: &Path) -> &[u8] {
path.as_os_str().as_encoded_bytes()
}
#[cfg(not(windows))]
fn shell() -> String {
"/bin/sh".to_owned()
}
#[cfg(windows)]
fn shell() -> String {
system32("cmd.exe")
}
#[cfg(windows)]
fn system32(name: &str) -> String {
format!("{}\\System32\\{name}", std::env::var("SystemRoot").unwrap())
}
const RUN: &str = if cfg!(windows) { "/C" } else { "-c" };
fn filter() -> (String, Vec<&'static str>) {
#[cfg(windows)]
return (system32("findstr.exe"), vec!["x"]);
#[cfg(not(windows))]
return (
shell(),
vec![
"-c",
r#"while read -r line; do case "$line" in *x*) echo "$line";; esac; done"#,
],
);
}
fn write_all(handle: impl AsHandle, mut buf: &[u8]) {
while !buf.is_empty() {
let n = io::write(handle.as_handle(), buf).unwrap();
assert!(n > 0);
buf = &buf[n..];
}
}
fn read_bytes(handle: impl AsHandle) -> Vec<u8> {
let mut out = Vec::new();
let mut buf = [0u8; 4096];
loop {
match io::read(handle.as_handle(), &mut buf) {
Ok(0) => break,
Ok(n) => out.extend_from_slice(&buf[..n]),
Err(error) if error.kind() == ErrorKind::BrokenPipe => break,
Err(error) => panic!("read failed: {error}"),
}
}
out
}
fn read_text(handle: impl AsHandle) -> String {
String::from_utf8_lossy(&read_bytes(handle)).replace('\r', "")
}
fn wait(child: &mut Child) -> ExitStatus {
let start = Instant::now();
loop {
if let Some(status) = child.try_wait().unwrap() {
assert_eq!(child.wait().unwrap(), status);
assert_eq!(child.try_wait().unwrap(), Some(status));
return status;
}
if start.elapsed() > Duration::from_secs(60) {
child.kill().unwrap();
panic!("the child did not exit");
}
std::thread::sleep(Duration::from_millis(2));
}
}
struct Output {
status: ExitStatus,
stdout: String,
stderr: String,
}
#[derive(Default)]
struct Options<'a> {
env: Option<&'a [String]>,
dir: Option<&'a Path>,
arg0: Option<&'a str>,
}
fn run_with(script: &str, options: &Options<'_>) -> Output {
let (out_read, out_write) = io::pipe().unwrap();
let (err_read, err_write) = io::pipe().unwrap();
let shell = shell();
let args = [RUN, script];
let mut command = Command::new(&shell)
.args(&args)
.stdin(Stdio::Null)
.stdout(Stdio::Handle(out_write.as_handle()))
.stderr(Stdio::Handle(err_write.as_handle()));
if let Some(env) = options.env {
command = command.env(env);
}
if let Some(dir) = options.dir {
command = command.current_dir(bytes(dir));
}
if let Some(arg0) = options.arg0 {
command = command.arg0(arg0);
}
let mut child = command.spawn().unwrap();
assert_ne!(child.id(), 0);
assert_ne!(child.id(), oscall::process::id());
drop((out_write, err_write));
let stdout = read_text(&out_read);
let stderr = read_text(&err_read);
Output {
status: wait(&mut child),
stdout,
stderr,
}
}
fn run(script: &str) -> Output {
run_with(script, &Options::default())
}
#[test]
fn exit_codes() {
for code in [0, 1, 7, 42, 255] {
let output = run(&format!("exit {code}"));
assert_eq!(output.status.code(), Some(code));
assert_eq!(output.status.success(), code == 0);
assert_eq!(output.stdout, "");
assert_eq!(output.stderr, "");
assert!(format!("{:?} {}", output.status, output.status).contains(&code.to_string()));
#[cfg(not(windows))]
{
use oscall::process::unix::ExitStatusExt;
assert_eq!(output.status.signal(), None);
assert!(!output.status.core_dumped());
}
}
}
#[test]
fn output_and_error() {
let script = if cfg!(windows) {
"echo out& echo err>&2"
} else {
"echo out; echo err >&2"
};
let output = run(script);
assert!(output.status.success());
assert_eq!(output.stdout, "out\n");
assert_eq!(output.stderr, "err\n");
}
#[test]
fn shared_output() {
let script = if cfg!(windows) {
"echo out& echo err>&2"
} else {
"echo out; echo err >&2"
};
let (read, write) = io::pipe().unwrap();
let shell = shell();
let mut child = Command::new(&shell)
.args(&[RUN, script])
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.stderr(Stdio::Handle(write.as_handle()))
.spawn()
.unwrap();
drop(write);
assert_eq!(read_text(&read), "out\nerr\n");
assert!(wait(&mut child).success());
}
#[test]
#[cfg(not(windows))]
fn arguments() {
let script = r#"for arg in "$@"; do printf '[%s]\n' "$arg"; done"#;
let args: Vec<Vec<u8>> = [
&b"-c"[..],
script.as_bytes(),
b"name",
b"plain",
b"two words",
b"",
b" spaces ",
b"tab\there",
br#"quote"inside"#,
br#""quoted""#,
br"back\slash",
br"trailing\",
br#"both\"of them\\"#,
b"'single'",
b"$HOME `id` $(id) ; & | > < * ? ~ # !",
b"%PATH% ^ %%",
"h\u{e9}llo \u{4e16}\u{754c} \u{1f600}".as_bytes(),
b"not utf-8: \xff\xfe\x80",
b"-n",
b"--",
]
.iter()
.map(|arg| arg.to_vec())
.collect();
let mut expected = Vec::new();
for arg in &args[3..] {
expected.push(b'[');
expected.extend_from_slice(arg);
expected.extend_from_slice(b"]\n");
}
let (read, write) = io::pipe().unwrap();
let mut child = Command::new("/bin/sh")
.args(&args)
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.spawn()
.unwrap();
drop(write);
let out = read_bytes(&read);
assert!(wait(&mut child).success());
assert_eq!(out, expected);
}
#[test]
#[cfg(not(windows))]
fn arg0() {
let output = run(r#"printf %s "$0""#);
assert_eq!(output.stdout, "/bin/sh");
let options = Options {
arg0: Some("another name"),
..Options::default()
};
let output = run_with(r#"printf %s "$0""#, &options);
assert_eq!(output.stdout, "another name");
}
#[test]
fn nul_is_refused() {
let shell = shell();
let invalid = |command: Command<'_>| {
assert_eq!(command.spawn().unwrap_err().kind(), ErrorKind::InvalidInput);
};
invalid(Command::new(&shell).args(&[RUN, "exit\0 0"]));
invalid(Command::new(&shell).args(&[RUN, "exit 0"]).env(&["A=\0"]));
invalid(
Command::new(&shell)
.args(&[RUN, "exit 0"])
.current_dir("a\0"),
);
invalid(Command::new(&shell).args(&[RUN, "exit 0"]).arg0("a\0"));
invalid(Command::new("a\0b"));
}
fn helper_env(mode: &str) -> Vec<Vec<u8>> {
let mut env: Vec<Vec<u8>> = std::env::vars_os()
.filter(|(name, _)| name != "OSCALL_TEST_HELPER")
.map(|(name, value)| [name.as_encoded_bytes(), b"=", value.as_encoded_bytes()].concat())
.collect();
env.push(format!("OSCALL_TEST_HELPER={mode}").into_bytes());
env
}
fn helper(mode: &str, args: &[Vec<u8>]) -> Option<ExitStatus> {
let exe = std::env::current_exe().ok()?;
let env = helper_env(mode);
let mut all: Vec<Vec<u8>> = ["--exact", "--nocapture", "helper_child_process", "--"]
.iter()
.map(|arg| arg.as_bytes().to_vec())
.collect();
all.extend_from_slice(args);
let spawned = Command::new(bytes(&exe))
.args(&all)
.env(&env)
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.spawn();
match spawned {
Ok(mut child) => Some(wait(&mut child)),
Err(error) if is_exec_format(error) => {
eprintln!("skipped: the system cannot execute {}", exe.display());
None
}
Err(error) => panic!("cannot run {}: {error}", exe.display()),
}
}
fn is_exec_format(error: Error) -> bool {
const ENOEXEC: i32 = 8;
cfg!(not(any(windows, target_os = "macos"))) && error.raw_os_error() == ENOEXEC
}
#[test]
fn arguments_through_std() {
let dir = tmp_dir("process_arguments_through_std");
let file = std::path::absolute(dir.join("args")).unwrap();
let args: Vec<Vec<u8>> = [
"plain",
"two words",
"",
" spaces ",
"tab\there",
r#"quote"inside"#,
r#""quoted""#,
r"back\slash",
r"trailing\",
r"trailing space\ ",
r"two trailing\\",
r#"both\"of them\\"#,
r#"\\"\\\"#,
"'single'",
"$HOME ; & | > < * ? ~ # ! ^ %PATH% %%",
"h\u{e9}llo \u{4e16}\u{754c} \u{1f600}",
"-n",
"--",
]
.iter()
.map(|arg| arg.as_bytes().to_vec())
.collect();
let mode = format!("args:{}", file.display());
let Some(status) = helper(&mode, &args) else {
return;
};
assert!(status.success(), "{status}");
let mut expected = Vec::new();
for arg in &args {
expected.extend_from_slice(arg);
expected.push(0);
}
assert_eq!(std::fs::read(&file).unwrap(), expected);
}
#[test]
#[cfg(windows)]
fn raw_command_line() {
use oscall::process::windows::CommandExt;
let (read, write) = io::pipe().unwrap();
let shell = shell();
let mut child = Command::new(&shell)
.args(&["ignored"])
.raw_command_line(r#"cmd /C echo "a b" c& exit 3"#)
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.spawn()
.unwrap();
drop(write);
assert_eq!(read_text(&read), "\"a b\" c\n");
assert_eq!(wait(&mut child).code(), Some(3));
}
#[test]
#[cfg(windows)]
fn batch_files() {
use oscall::process::windows::CommandExt;
let dir = tmp_dir("process_batch_files");
let dir = std::path::absolute(&dir).unwrap();
let marker = dir.join("marker");
let inject = format!("\"&echo x>{}", marker.display());
for name in [
"x.bat",
"x.cmd",
"X.BAT",
"x.Cmd",
"x.bat.",
"x.bat ",
"x.cmd. . ",
"x.bat\\.",
"x.bat/.",
"sub\\..\\x.bat",
".\\x.cmd\\",
] {
let file = dir.join(if name.to_ascii_lowercase().contains("cmd") {
"x.cmd"
} else {
"x.bat"
});
std::fs::write(&file, "@exit /b 7\r\n").unwrap();
let program = dir.join(name);
let error = Command::new(bytes(&program))
.args(&[inject.as_str()])
.stdin(Stdio::Null)
.spawn()
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{name}: {error:?}");
let error = Command::new(bytes(&program)).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{name}: {error:?}");
let error = Command::new(name).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{name}: {error:?}");
}
assert!(!marker.exists());
for name in ["x.bat.exe", "bat", "x.batx", ".bat\\x"] {
let error = Command::new(name).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{name}: {error:?}");
}
let line = format!("cmd /C \"{}\"", dir.join("x.bat").display());
let shell = shell();
let mut child = Command::new(&shell)
.raw_command_line(&line)
.stdin(Stdio::Null)
.spawn()
.unwrap();
assert_eq!(wait(&mut child).code(), Some(7));
}
#[test]
fn invalid_environment() {
let shell = shell();
for vars in [
&[""][..],
&["A=1", "", "B=2"],
&["A=1", "B"],
&["="],
&["=B"],
&["A=1", "B=2\0"],
] {
let error = Command::new(&shell)
.args(&[RUN, "exit 0"])
.env(vars)
.stdin(Stdio::Null)
.spawn()
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{vars:?}: {error:?}");
}
let script = if cfg!(windows) {
"echo [%OSCALL_A%][%OSCALL_B%]"
} else {
r#"echo "[${OSCALL_A-unset}][$OSCALL_B]""#
};
let mut vars = vec![
"OSCALL_A=".to_owned(),
"OSCALL_B=b".to_owned(),
"=Q:=x".to_owned(),
];
if cfg!(windows) {
vars.push(format!(
"SystemRoot={}",
std::env::var("SystemRoot").unwrap()
));
}
let options = Options {
env: Some(&vars),
..Options::default()
};
let output = run_with(script, &options);
assert!(output.status.success(), "{}", output.stderr);
let expected = if cfg!(windows) {
"[%OSCALL_A%][b]\n"
} else {
"[][b]\n"
};
assert_eq!(output.stdout, expected);
}
#[test]
fn exit_and_abort() {
let Some(status) = helper("exit:0", &[]) else {
return;
};
assert!(status.success());
let status = helper("exit:37", &[]).unwrap();
assert_eq!(status.code(), Some(37));
assert!(!status.success());
let status = helper("abort", &[]).unwrap();
assert!(!status.success());
#[cfg(windows)]
assert_eq!(status.code(), Some(0xc000_0409_u32 as i32));
#[cfg(not(windows))]
{
use oscall::process::unix::ExitStatusExt;
const SIGABRT: i32 = 6;
assert_eq!(status.code(), None);
assert_eq!(status.signal(), Some(SIGABRT));
}
}
#[test]
fn child_ids() {
let dir = tmp_dir("process_child_ids");
let file = std::path::absolute(dir.join("ids")).unwrap();
let mode = format!("ids:{}", file.display());
if helper(&mode, &[]).is_none() {
return;
}
let ids = std::fs::read_to_string(&file).unwrap();
let (id, parent) = ids.split_once(' ').unwrap();
assert_ne!(id.parse::<u32>().unwrap(), oscall::process::id());
assert_eq!(parent.parse::<u32>().unwrap(), oscall::process::id());
}
#[test]
fn explicit_environment() {
let script = if cfg!(windows) {
"echo %OSCALL_A%-%OSCALL_B%-%OSCALL_C%"
} else {
r#"echo "$OSCALL_A-$OSCALL_B-${OSCALL_C-unset}-${HOME-unset}""#
};
let vars = vec![
"OSCALL_A=two words".to_owned(),
"OSCALL_B=h\u{e9}=\u{4e16}".to_owned(),
];
let options = Options {
env: Some(&vars),
..Options::default()
};
let output = run_with(script, &options);
assert!(output.status.success());
if cfg!(windows) {
let out = &output.stdout;
assert!(out.starts_with("two words-h"), "{out:?}");
assert!(out.ends_with("-%OSCALL_C%\n"), "{out:?}");
} else {
assert_eq!(output.stdout, "two words-h\u{e9}=\u{4e16}-unset-unset\n");
}
let script = if cfg!(windows) {
"echo %OSCALL_A%-%SystemRoot%"
} else {
r#"echo "${OSCALL_A-unset}-${HOME-unset}""#
};
let options = Options {
env: Some(&[]),
..Options::default()
};
let output = run_with(script, &options);
assert!(output.status.success());
let expected = if cfg!(windows) {
"%OSCALL_A%-%SystemRoot%\n"
} else {
"unset-unset\n"
};
assert_eq!(output.stdout, expected);
}
#[test]
fn inherited_environment() {
let name = if cfg!(windows) { "SystemRoot" } else { "PATH" };
let value = std::env::var(name).unwrap();
let script = if cfg!(windows) {
"echo %SystemRoot%"
} else {
r#"echo "$PATH""#
};
let output = run(script);
assert!(output.status.success());
assert_eq!(output.stdout, format!("{value}\n"));
}
#[test]
fn working_directory() {
let dir = tmp_dir("process_working_directory");
let script = if cfg!(windows) {
"echo x> marker"
} else {
"echo x > marker"
};
let options = Options {
dir: Some(&dir),
..Options::default()
};
let output = run_with(script, &options);
assert!(output.status.success(), "{}", output.stderr);
assert!(dir.join("marker").is_file());
assert!(!PathBuf::from("marker").exists());
let shell = shell();
let missing = dir.join("missing");
let result = Command::new(&shell)
.args(&[RUN, "exit 0"])
.current_dir(bytes(&missing))
.spawn();
let kind = result.unwrap_err().kind();
if cfg!(windows) {
assert_eq!(kind, ErrorKind::NotADirectory);
} else {
assert_eq!(kind, ErrorKind::NotFound);
}
}
#[test]
#[cfg(not(windows))]
fn relative_program() {
let dir = tmp_dir("process_relative_program");
let sub = dir.join("sub");
std::fs::create_dir(&sub).unwrap();
let script = dir.join("script");
assert!(script.is_relative());
std::fs::write(&script, "#!/bin/sh\necho \"$0\" > marker\nexit 5\n").unwrap();
let executable = oscall::fs::Permissions::from_mode(0o755);
oscall::fs::set_permissions(bytes(&script), executable).unwrap();
let command = Command::new(bytes(&script))
.stdin(Stdio::Null)
.current_dir(bytes(&sub));
let mut child = loop {
match command.spawn() {
Ok(child) => break child,
Err(error) if error.kind() == ErrorKind::ExecutableFileBusy => {
std::thread::sleep(Duration::from_millis(2));
}
Err(error) => panic!("{error:?}"),
}
};
assert_eq!(wait(&mut child).code(), Some(5));
let seen = std::fs::read_to_string(sub.join("marker")).unwrap();
let absolute = std::path::absolute(&script).unwrap();
assert_eq!(seen.trim_end(), absolute.to_str().unwrap());
assert!(!dir.join("marker").exists());
let (read, write) = io::pipe().unwrap();
std::fs::write(&script, "#!/bin/sh\necho \"$0\"\n").unwrap();
let command = Command::new(bytes(&script))
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()));
let mut child = loop {
match command.spawn() {
Ok(child) => break child,
Err(error) if error.kind() == ErrorKind::ExecutableFileBusy => {
std::thread::sleep(Duration::from_millis(2));
}
Err(error) => panic!("{error:?}"),
}
};
drop(write);
assert_eq!(read_text(&read).trim_end(), script.to_str().unwrap());
assert!(wait(&mut child).success());
}
#[test]
#[cfg(windows)]
fn relative_program() {
let dir = tmp_dir("process_relative_program");
let exe = std::env::current_exe().unwrap();
let here = std::env::current_dir().unwrap();
let Ok(relative) = exe.strip_prefix(&here) else {
eprintln!("skipped: {} is not under {}", exe.display(), here.display());
return;
};
let env = helper_env("exit:5");
let mut child = Command::new(bytes(relative))
.args(&["--exact", "--nocapture", "helper_child_process"])
.env(&env)
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.current_dir(bytes(&dir))
.spawn()
.unwrap();
assert_eq!(wait(&mut child).code(), Some(5));
}
#[test]
fn found_program() {
let Some(path) = std::env::var_os("PATH") else {
eprintln!("skipped: no PATH");
return;
};
let name = if cfg!(windows) { "cmd" } else { "sh" };
let program = oscall::process::find_program_vec(name, path.as_encoded_bytes()).unwrap();
assert!(std::path::Path::new(std::str::from_utf8(&program).unwrap()).is_file());
let mut child = Command::new(&program)
.args(&[RUN, "exit 3"])
.stdin(Stdio::Null)
.spawn()
.unwrap();
assert_eq!(wait(&mut child).code(), Some(3));
}
#[test]
#[cfg(windows)]
fn sorted_environment() {
let vars = vec![
format!("SystemRoot={}", std::env::var("SystemRoot").unwrap()),
"OSCALL_ZZ=1".to_owned(),
"oscall_mm=2".to_owned(),
"OSCALL_AA=3".to_owned(),
"oscall_b=4".to_owned(),
"OSCALL_B=5".to_owned(),
"=X:=X:\\".to_owned(),
];
let options = Options {
env: Some(&vars),
..Options::default()
};
let output = run_with("set", &options);
assert!(output.status.success(), "{}", output.stderr);
let ours: Vec<&str> = output
.stdout
.lines()
.filter(|line| line.to_ascii_lowercase().starts_with("oscall_"))
.collect();
assert_eq!(
ours,
[
"OSCALL_AA=3",
"oscall_b=4",
"OSCALL_B=5",
"oscall_mm=2",
"OSCALL_ZZ=1"
],
"{}",
output.stdout
);
}
#[test]
fn child_resource_usage() {
let script = if cfg!(windows) {
"for /L %i in (1,1,30000) do @rem"
} else {
"i=0; while [ $i -lt 100000 ]; do i=$((i+1)); done"
};
let shell = shell();
let mut child = Command::new(&shell)
.args(&[RUN, script])
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.spawn()
.unwrap();
assert_eq!(child.resource_usage(), None);
let started = Instant::now();
assert!(wait(&mut child).success());
let elapsed = started.elapsed();
let usage = child
.resource_usage()
.expect("no usage for a child waited for");
assert_eq!(child.resource_usage(), Some(usage));
let peak = usage.max_resident_memory();
assert!(peak < 1 << 40, "{usage:?}");
if !cfg!(any(target_os = "linux", target_os = "fullrust")) {
assert!(peak > 0, "{usage:?}");
}
let total = usage.user_time() + usage.system_time();
assert!(
total <= 2 * elapsed + Duration::from_secs(1),
"{usage:?} {elapsed:?}"
);
if !cfg!(windows) {
assert!(total > Duration::ZERO, "{usage:?}");
}
let (mut child, _input) = blocked_child();
child.kill().unwrap();
child.wait().unwrap();
assert!(child.resource_usage().is_some());
}
#[test]
fn exists_and_kill() {
let (mut child, _input) = blocked_child();
let pid = child.id();
assert_eq!(oscall::process::exists(pid), Ok(true));
oscall::process::kill(pid).unwrap();
let status = child.wait().unwrap();
#[cfg(windows)]
assert_eq!(status.code(), Some(1));
#[cfg(not(windows))]
{
use oscall::process::unix::{ExitStatusExt, SIGKILL};
assert_eq!(status.signal(), Some(SIGKILL));
}
assert_eq!(oscall::process::exists(pid), Ok(false));
let error = oscall::process::kill(pid).unwrap_err();
let expected = if cfg!(windows) {
ErrorKind::InvalidInput
} else {
ErrorKind::NoSuchProcess
};
assert_eq!(error.kind(), expected, "{error:?}");
}
#[test]
#[cfg(windows)]
fn new_process_group() {
use oscall::process::windows::CommandExt;
let (read, write) = io::pipe().unwrap();
let shell = shell();
let mut child = Command::new(&shell)
.args(&[RUN, "echo out& exit 3"])
.new_process_group()
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.spawn()
.unwrap();
drop(write);
assert_eq!(read_text(&read), "out\n");
assert_eq!(wait(&mut child).code(), Some(3));
}
#[cfg(not(windows))]
fn blocked_child_with(
configure: impl for<'a> FnOnce(Command<'a>) -> Command<'a>,
) -> (Child, OwnedHandle) {
let (read, write) = io::pipe().unwrap();
let (program, args) = filter();
let command = Command::new(&program)
.args(&args)
.stdin(Stdio::Handle(read.as_handle()))
.stdout(Stdio::Null)
.stderr(Stdio::Null);
(configure(command).spawn().unwrap(), write)
}
#[test]
#[cfg(not(windows))]
fn signal_by_pid() {
use oscall::process::unix::{self, ExitStatusExt};
let (mut child, _input) = blocked_child();
let pid = child.id();
unix::send_signal(pid, 0).unwrap();
assert_eq!(child.try_wait().unwrap(), None);
let error = unix::send_signal(pid, 1000).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
unix::send_signal(pid, unix::SIGUSR1).unwrap();
assert_eq!(child.wait().unwrap().signal(), Some(unix::SIGUSR1));
let error = unix::send_signal(pid, 0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");
for pid in [0, u32::MAX, 1 << 31] {
let error = unix::send_signal(pid, 0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let error = unix::send_signal_to_group(pid, 0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let error = unix::process_group(pid).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
let error = unix::session(pid).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
let error = unix::send_signal_to_group(1, 0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
}
#[test]
#[cfg(not(windows))]
fn process_groups() {
use oscall::process::unix::{self, CommandExt, ExitStatusExt};
let own = oscall::process::id();
let group = unix::process_group(own).unwrap();
let session = unix::session(own).unwrap();
assert_ne!(group, 0);
assert_ne!(session, 0);
let (mut child, _input) = blocked_child();
assert_eq!(unix::process_group(child.id()), Ok(group));
assert_eq!(unix::session(child.id()), Ok(session));
child.kill().unwrap();
child.wait().unwrap();
let (mut leader, _leader_input) = blocked_child_with(|command| command.process_group(0));
assert_eq!(unix::process_group(leader.id()), Ok(leader.id()));
assert_eq!(unix::session(leader.id()), Ok(session));
let id = leader.id();
let (mut member, _member_input) = blocked_child_with(|command| command.process_group(id));
assert_eq!(unix::process_group(member.id()), Ok(leader.id()));
unix::send_signal_to_group(leader.id(), 0).unwrap();
unix::send_signal_to_group(leader.id(), unix::SIGTERM).unwrap();
assert_eq!(leader.wait().unwrap().signal(), Some(unix::SIGTERM));
assert_eq!(member.wait().unwrap().signal(), Some(unix::SIGTERM));
let error = unix::send_signal_to_group(id, 0).unwrap_err();
assert_eq!(error.kind(), ErrorKind::NoSuchProcess, "{error:?}");
let (read, _write) = io::pipe().unwrap();
let (program, args) = filter();
let error = Command::new(&program)
.args(&args)
.stdin(Stdio::Handle(read.as_handle()))
.process_group(id)
.spawn()
.unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let (mut child, _input) =
blocked_child_with(|command| command.new_session().process_group(group));
assert_eq!(unix::session(child.id()), Ok(child.id()));
assert_eq!(unix::process_group(child.id()), Ok(child.id()));
child.kill().unwrap();
child.wait().unwrap();
}
#[test]
fn pipes() {
let (in_read, in_write) = io::pipe().unwrap();
let (out_read, out_write) = io::pipe().unwrap();
let (program, args) = filter();
let mut child = Command::new(&program)
.args(&args)
.stdin(Stdio::Handle(in_read.as_handle()))
.stdout(Stdio::Handle(out_write.as_handle()))
.spawn()
.unwrap();
drop((in_read, out_write));
assert_eq!(child.try_wait().unwrap(), None);
write_all(&in_write, b"x one\nno\nx two\n");
drop(in_write);
assert_eq!(read_text(&out_read), "x one\nx two\n");
assert!(wait(&mut child).success());
}
#[test]
fn files() {
let dir = tmp_dir("process_files");
std::fs::write(dir.join("in"), "x one\nno\nx two\n").unwrap();
let input = File::open(dir.join("in")).unwrap();
let output = File::create(dir.join("out")).unwrap();
let (program, args) = filter();
let mut child = Command::new(&program)
.args(&args)
.stdin(Stdio::Handle(handle_of(&input)))
.stdout(Stdio::Handle(handle_of(&output)))
.stderr(Stdio::Null)
.spawn()
.unwrap();
assert!(wait(&mut child).success());
let text = std::fs::read_to_string(dir.join("out")).unwrap();
assert_eq!(text.replace('\r', ""), "x one\nx two\n");
assert!(!io::is_inheritable(handle_of(&output)).unwrap());
}
#[test]
fn null() {
let (program, args) = filter();
let mut child = Command::new(&program)
.args(&args)
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.spawn()
.unwrap();
assert!(wait(&mut child).code().is_some());
let script = if cfg!(windows) {
"echo out& echo err>&2& exit 3"
} else {
"echo out; echo err >&2; exit 3"
};
let shell = shell();
let mut child = Command::new(&shell)
.args(&[RUN, script])
.stdin(Stdio::Null)
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.spawn()
.unwrap();
assert_eq!(wait(&mut child).code(), Some(3));
}
#[test]
fn invalid_handle() {
#[cfg(windows)]
let values = [0x7ffc_0000usize as oscall::RawHandle];
#[cfg(not(windows))]
let values: [oscall::RawHandle; 2] = [-1, 1_000_000];
let shell = shell();
for raw in values {
let handle = unsafe { oscall::BorrowedHandle::borrow_raw(raw) };
for target in 0..3 {
let mut command = Command::new(&shell).args(&[RUN, "exit 0"]);
command = match target {
0 => command.stdin(Stdio::Handle(handle)),
1 => command.stdout(Stdio::Handle(handle)),
_ => command.stderr(Stdio::Handle(handle)),
};
let error = command.spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::BadHandle, "{error:?}");
}
}
}
fn blocked_child() -> (Child, OwnedHandle) {
let (read, write) = io::pipe().unwrap();
let (program, args) = filter();
let child = Command::new(&program)
.args(&args)
.stdin(Stdio::Handle(read.as_handle()))
.stdout(Stdio::Null)
.stderr(Stdio::Null)
.spawn()
.unwrap();
(child, write)
}
#[test]
fn try_wait() {
let (mut child, input) = blocked_child();
for _ in 0..3 {
assert_eq!(child.try_wait().unwrap(), None);
}
std::thread::sleep(Duration::from_millis(20));
assert_eq!(child.try_wait().unwrap(), None);
drop(input);
let status = wait(&mut child);
assert!(status.code().is_some());
assert_eq!(child.try_wait().unwrap(), Some(status));
assert_eq!(child.wait().unwrap(), status);
}
#[test]
fn kill() {
let (mut child, _input) = blocked_child();
assert_eq!(child.try_wait().unwrap(), None);
child.kill().unwrap();
let status = child.wait().unwrap();
assert!(!status.success());
#[cfg(windows)]
assert_eq!(status.code(), Some(1));
#[cfg(not(windows))]
{
use oscall::process::unix::{ExitStatusExt, SIGKILL};
assert_eq!(status.code(), None);
assert_eq!(status.signal(), Some(SIGKILL));
assert!(!status.core_dumped());
}
child.kill().unwrap();
assert_eq!(child.try_wait().unwrap(), Some(status));
assert_eq!(child.wait().unwrap(), status);
}
#[test]
fn kill_after_exit() {
let (mut child, input) = blocked_child();
drop(input);
std::thread::sleep(Duration::from_millis(200));
child.kill().unwrap();
let _ = child.wait().unwrap();
child.kill().unwrap();
}
#[test]
#[cfg(not(windows))]
fn signals() {
use oscall::process::unix::{self, ChildExt, ExitStatusExt};
let (mut child, _input) = blocked_child();
child.send_signal(0).unwrap();
assert_eq!(child.try_wait().unwrap(), None);
child.send_signal(unix::SIGTERM).unwrap();
let status = child.wait().unwrap();
assert_eq!(status.signal(), Some(unix::SIGTERM));
assert_eq!(status.code(), None);
assert!(!status.success());
assert!(format!("{status}").contains("signal"));
assert_eq!(
child.send_signal(unix::SIGTERM).unwrap_err().kind(),
ErrorKind::NoSuchProcess
);
let (mut child, input) = blocked_child();
child.send_signal(unix::SIGSTOP).unwrap();
assert_eq!(child.try_wait().unwrap(), None);
child.send_signal(unix::SIGCONT).unwrap();
assert_eq!(child.try_wait().unwrap(), None);
child.send_signal(unix::SIGKILL).unwrap();
assert_eq!(child.wait().unwrap().signal(), Some(unix::SIGKILL));
drop(input);
assert_eq!(unix::SIGQUIT, 3);
for signal in [unix::SIGHUP, unix::SIGINT, unix::SIGUSR1, unix::SIGUSR2] {
let (mut child, _input) = blocked_child();
child.send_signal(signal).unwrap();
assert_eq!(child.wait().unwrap().signal(), Some(signal));
}
}
#[test]
#[cfg(not(windows))]
fn signal_dispositions() {
use oscall::process::unix::ExitStatusExt;
const SIGPIPE: i32 = 13;
let (read, write) = io::pipe().unwrap();
drop(read);
let mut child = Command::new("/bin/sh")
.args(&["-c", "echo one; echo two; exit 0"])
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.stderr(Stdio::Null)
.spawn()
.unwrap();
let status = wait(&mut child);
assert_eq!(status.signal(), Some(SIGPIPE), "{status}");
}
#[test]
fn missing_program() {
let dir = tmp_dir("process_missing_program");
for path in [dir.join("missing"), dir.join("missing").join("program")] {
let error = Command::new(bytes(&path)).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
}
let name = if cfg!(windows) { "cmd.exe" } else { "sh" };
let error = Command::new(name).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::NotFound, "{error:?}");
let error = Command::new("").spawn().unwrap_err();
assert!(
matches!(error.kind(), ErrorKind::NotFound | ErrorKind::InvalidInput),
"{error:?}"
);
}
#[test]
fn not_executable() {
let dir = tmp_dir("process_not_executable");
let error = Command::new(bytes(&dir)).spawn().unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let file = dir.join("script");
std::fs::write(&file, "#!/bin/sh\nexit 5\n").unwrap();
let command = Command::new(bytes(&file)).stdin(Stdio::Null);
let error = command.spawn().unwrap_err();
if cfg!(windows) {
const ERROR_BAD_EXE_FORMAT: i32 = 193;
assert_eq!(error.raw_os_error(), ERROR_BAD_EXE_FORMAT);
return;
}
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
let executable = oscall::fs::Permissions::from_mode(0o755);
oscall::fs::set_permissions(bytes(&file), executable).unwrap();
assert!(format!("{command:?}").contains("script"));
let spawn = |command: &Command<'_>| loop {
match command.spawn() {
Ok(child) => break child,
Err(error) if error.kind() == ErrorKind::ExecutableFileBusy => {
std::thread::sleep(Duration::from_millis(2));
}
Err(error) => panic!("{error:?}"),
}
};
for _ in 0..2 {
let mut child = spawn(&command);
assert_eq!(wait(&mut child).code(), Some(5));
}
let mut child = spawn(&command.clone());
assert_eq!(wait(&mut child).code(), Some(5));
}
#[test]
fn nothing_else_is_inherited() {
let (read, write) = io::pipe().unwrap();
io::set_inheritable(&write, true).unwrap();
let (mut child, input) = blocked_child();
drop(write);
let (sender, receiver) = mpsc::channel();
let reader = std::thread::spawn(move || {
let mut buf = [0u8; 1];
let _ = sender.send(io::read(&read, &mut buf));
});
let result = receiver.recv_timeout(Duration::from_secs(20));
child.kill().unwrap();
child.wait().unwrap();
drop(input);
reader.join().unwrap();
match result {
Ok(Ok(0)) => {}
Ok(Err(error)) if error.kind() == ErrorKind::BrokenPipe => {}
other => panic!("the child inherited the pipe: {other:?}"),
}
}
#[test]
#[cfg(any(target_os = "linux", target_os = "fullrust", windows))]
fn child_handle() {
let (mut child, input) = blocked_child();
assert!(!io::is_inheritable(child.as_handle()).unwrap());
let copy = io::duplicate(&child).unwrap();
drop(input);
wait(&mut child);
drop(copy);
}
#[test]
fn concurrent_spawns() {
let threads: Vec<_> = (0..8)
.map(|thread| {
std::thread::spawn(move || {
for round in 0..8 {
let token = thread * 10 + round;
let script = if cfg!(windows) {
format!("echo {token}& exit {token}")
} else {
format!("echo {token}; exit {token}")
};
let output = run(&script);
assert_eq!(output.stdout, format!("{token}\n"));
assert_eq!(output.stderr, "");
assert_eq!(output.status.code(), Some(token));
}
})
})
.collect();
for thread in threads {
thread.join().unwrap();
}
}
}