Skip to content

std::process::Command::env_remove causes Command behave differently on Windows #90515

Closed
@fanzeyi

Description

@fanzeyi

With the following code:

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

fn main() -> () {
    println!("I am {:?}", current_exe().unwrap());

    if std::env::var("SPAWN_SUB").is_ok() {
        let mut cmd = Command::new("test.foo");
 
        // Comment out this line to see the expected behavior
        cmd.env_remove("SPAWN_SUB");

        println!("Executing {:?}", &cmd);

        cmd.status().unwrap();
    } else {
        println!("I am a subprocess");
    }
}

With this setup:

$ cargo build --release
$ cp .\target\release\subprocess-bug.exe test.exe
$ cargo run --release

I expected to see this happen:

The valid executable to run in this case are test.foo, test.foo.exe, test.foo.cmd, .... Since none of these exist, it should give me an error. This is also the behavior when the env_remove line is commented out. Like this:

$ $Env:SPAWN_SUB="1"; cargo run --release
   Compiling subprocess-bug v0.1.0 (C:\Users\zeyi\subprocess-bug)
    Finished release [optimized] target(s) in 0.44s
     Running `target\release\subprocess-bug.exe`
I am "C:\\Users\\zeyi\\subprocess-bug\\target\\release\\subprocess-bug.exe"
Executing "test.foo"
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." }', src\main.rs:14:22
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Instead, this happened:

test.exe is incorrectly being spawned.

$ $Env:SPAWN_SUB="1"; cargo run --release
   Compiling subprocess-bug v0.1.0 (C:\Users\zeyi\subprocess-bug)
    Finished release [optimized] target(s) in 0.45s
     Running `target\release\subprocess-bug.exe`
I am "C:\\Users\\zeyi\\subprocess-bug\\target\\release\\subprocess-bug.exe"
Executing "test.foo"
I am "C:\\Users\\zeyi\\subprocess-bug\\test.exe"
I am a subprocess

Meta

rustc --version --verbose:

rustc --version --verbose
rustc 1.55.0 (c8dfcfe04 2021-09-06)
binary: rustc
commit-hash: c8dfcfe046a7680554bf4eb612bad840e7631c4b
commit-date: 2021-09-06
host: x86_64-pc-windows-msvc
release: 1.55.0
LLVM version: 12.0.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions