Skip to content

How do I merge stdout and stderr of a child process? #3419

Answered by Darksonn
Darksonn asked this question in Q&A
Discussion options

You must be logged in to vote

The general approach for merging the two streams is the following:

  1. Put stdout and stderr into tokio::io::BufReader.
  2. Put the buffered streams into tokio::io::Lines.
  3. Wrap it in tokio_stream::wrappers::LinesStream.
  4. Merge them with tokio_stream::StreamExt::merge.

This gives the following code:

use tokio::io::{AsyncBufReadExt, BufReader};
use tokio_stream::StreamExt;
use tokio_stream::wrappers::LinesStream;

// Variable of type tokio::process::Child.
let child = ...;

// Take ownership of stdout and stderr from child.
let stdout = child.stdout.take().unwrap();
let stderr = child.stderr.take().unwrap();

// Wrap them up and merge them.
let stdout = LinesStream::new(BufReader::new(stdout).lines()

Replies: 2 comments 1 reply

Comment options

Darksonn
Jan 13, 2021
Maintainer Author

You must be logged in to vote
0 replies
Answer selected by Darksonn
Comment options

You must be logged in to vote
1 reply
@andrewbaxter
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants