Skip to content

Conversation

Pistonight
Copy link
Contributor

Motivation

See #7249 (comment), since the with closure is only called once, it can be upgraded to FnOnce to allow mutation.

Solution

Changed Fn to FnOnce in Command::spawn_with

Tested with the following code

use tokio::process::{Command};
use std::process::Stdio;

#[tokio::main]
async fn main() {
    let mut std_io: Option<Stdio> = None;
    let hello = Command::new("echo")
        .arg("Hello, world!")
        .stdout(Stdio::piped())
        .spawn_with(|cmd| {
            let mut child = cmd.spawn()?;
            std_io = child.stdout.take().map(Stdio::from);
            Ok(child)
        })
        .expect("failed echo command");
    
    let reverse = Command::new("rev")
        .stdin(std_io.take().unwrap())
        .output().await.unwrap();
    
    assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");
}

*I don't know all the implications of piping stdout into stdin in this way versus the one in the module documentation that uses TryInto<Stdio> on the spawned child. This PR isn't intended to solve that problem anyway, so I didn't add any automated test.

@Darksonn Darksonn added A-tokio Area: The main tokio crate M-process Module: tokio/process labels Aug 3, 2025
Copy link
Contributor

@Darksonn Darksonn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks.

@Darksonn Darksonn enabled auto-merge (squash) August 3, 2025 18:27
@Darksonn Darksonn merged commit 2403b91 into tokio-rs:master Aug 3, 2025
97 checks passed
@Darksonn Darksonn mentioned this pull request Oct 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-tokio Area: The main tokio crate M-process Module: tokio/process

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants