How does child process stdout work?

In my integration test, I'm starting a http server as a child process, then I try to capture the stdout of the child process.

Because the child process won't exit until it's killed explicitly, I am trying to use the following to capture its stdout:

    let mut server = Command::new(bin_path.into_os_string())
        .expect("Failed to start server");
    let mut buffer = String::new();
    let f = server.stdout.as_mut().expect("Failed to get stdout");
    f.read_to_string(&mut buffer).expect("Failed to read ");

Looks like I have to call .stdout(Stdio::piped()) before spawn(), i.e. the default behavior does not capture the child process's stdout. Why is that?

Also, it seems that Stdio::inherit() does not work in this case (i.e. will fail to capture the stdout). Why is that? When using inherit(), the test output does not include any output from the child either. How do you get the child process stdout when using inherit() ?

When using inherit, the subprocess' output will be sent to whereever your process' stdout is sent to.

1 Like

Thanks. I didn't know about --nocapture for cargo test. Now I can use inherit and --nocapture to see the stdout.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.