Skip to content

Command::env()/env_remove() freeze the parent's environment #33183

@oconnor663

Description

@oconnor663

An example:

use std::process::Command;
use std::env;

fn main() {
    // Create a command to echo $foo.
    let mut c = Command::new("bash");
    c.arg("-c").arg("echo $foo");

    // Set an unrelated variable. This caches the current environment.
    c.env("UNRELATED_VARIABLE", "junk");

    // Define $foo in the parent. This has no effect on the child,
    // because of the line above!
    env::set_var("foo", "FOO IS DEFINED!!!");

    c.spawn().unwrap();
}

This program will run echo $foo, which prints an empty line because $foo is not defined in the child. But if we delete the line that sets $UNRELATED_VARIABLE and run again, we see FOO IS DEFINED!!! in the child's output.

The problem is that (at least in the unix implementation) the init_env_map function caches the parent's environment the first time it's called. My preferred behavior would be that Command never caches anything from the parent, and instead reads the environment at the time the child is spawned. Does anyone know of code relying on the current behavior?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions