expression

Restrict the environment of a child

A child normally inherits environment settings. Clearing and supplying an explicit allowlist limits accidental exposure of parent variables, but does not enforce filesystem, network or privilege isolation. Use an absolute trusted executable path rather than relying on PATH. This fixture changes only the child environment, never the global parent environment. Expected stdout (not executed): mode: demo extra: false Common mistake: Equating environment filtering with a security sandbox. Run only in the isolated fixture runner, not a public code playground.

Formal Syntax & Structure

rust syntaxrust
Command::env_clear().env(key, value)

Working Example

Example Snippetrust
use std::{env, io, process::Command};fn main() -> io::Result<()> {    if env::args().nth(1).as_deref() == Some("worker") {        println!("mode: {}", env::var("BM_MODE").unwrap());        println!("extra: {}", env::var_os("BM_EXTRA").is_some()); return Ok(());    }    let out = Command::new(env::current_exe()?).arg("worker")        .env_clear().env("BM_MODE", "demo").output()?;    assert!(out.status.success()); print!("{}", String::from_utf8_lossy(&out.stdout));    Ok(())}
Rust Reference