How can I wait for a Rust `Child` process whose stdout has been piped to another?
Asked Answered
T

1

5

I want to implement yes | head -n 1 in Rust, properly connecting pipes and checking exit statuses: i.e., I want to be able to determine that yes exits due to SIGPIPE and that head completes normally. The pipe functionality is easy (Rust Playground):

use std::process;

fn a() -> std::io::Result<()> {
    let child_1 = process::Command::new("yes")
        .arg("abracadabra")
        .stdout(process::Stdio::piped())
        .spawn()?;
    let pipe: process::ChildStdout = child_1.stdout.unwrap();
    let child_2 = process::Command::new("head")
        .args(&["-n", "1"])
        .stdin(pipe)
        .stdout(process::Stdio::piped())
        .spawn()?;
    let output = child_2.wait_with_output()?;
    let result = String::from_utf8_lossy(&output.stdout);
    assert_eq!(result, "abracadabra\n");
    println!("Good from 'a'.");
    Ok(())
}

But while we can wait on child_2 at any point, the declaration of pipe moves child_1, and so it’s not clear how to wait on child_1. If we were to simply add child_1.wait()? before the assert_eq!, we’d hit a compile-time error:

error[E0382]: borrow of moved value: `child_1`
  --> src/main.rs:15:5
   |
8  |     let pipe: process::ChildStdout = child_1.stdout.unwrap();
   |                                      -------------- value moved here
...
15 |     child_1.wait()?;
   |     ^^^^^^^ value borrowed here after partial move
   |
   = note: move occurs because `child_1.stdout` has type `std::option::Option<std::process::ChildStdout>`, which does not implement the `Copy` trait

We can manage to wait with unsafe and platform-specific functionality (Rust Playground):

use std::process;

fn b() -> std::io::Result<()> {
    let mut child_1 = process::Command::new("yes")
        .arg("abracadabra")
        .stdout(process::Stdio::piped())
        .spawn()?;
    use std::os::unix::io::{AsRawFd, FromRawFd};
    let pipe: process::Stdio =
        unsafe { FromRawFd::from_raw_fd(child_1.stdout.as_ref().unwrap().as_raw_fd()) };
    let mut child_2 = process::Command::new("head")
        .args(&["-n", "1"])
        .stdin(pipe)
        .stdout(process::Stdio::piped())
        .spawn()?;
    println!("child_1 exited with: {:?}", child_1.wait().unwrap());
    println!("child_2 exited with: {:?}", child_2.wait().unwrap());
    let mut result_bytes: Vec<u8> = Vec::new();
    std::io::Read::read_to_end(child_2.stdout.as_mut().unwrap(), &mut result_bytes)?;
    let result = String::from_utf8_lossy(&result_bytes);
    assert_eq!(result, "abracadabra\n");
    println!("Good from 'b'.");
    Ok(())
}

This prints:

child_1 exited with: ExitStatus(ExitStatus(13))
child_2 exited with: ExitStatus(ExitStatus(0))
Good from 'b'.

This is good enough for the purposes of this question, but surely there must be a safe and portable way to do this.

For comparison, here is how I would approach the task in C (without bothering to capture child_2’s output):

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define FAILIF(e, msg) do { if (e) { perror(msg); return 1; } } while (0)

void describe_child(const char *name, int status) {
    if (WIFEXITED(status)) {
        fprintf(stderr, "%s exited %d\n", name, WEXITSTATUS(status));
    } else if (WIFSIGNALED(status)) {
        fprintf(stderr, "%s signalled %d\n", name, WTERMSIG(status));
    } else {
        fprintf(stderr, "%s fate unknown\n", name);
    }
}

int main(int argc, char **argv) {
    int pipefd[2];
    FAILIF(pipe(pipefd), "pipe");

    pid_t pid_1 = fork();
    FAILIF(pid_1 < 0, "child_1: fork");
    if (!pid_1) {
        FAILIF(dup2(pipefd[1], 1) == -1, "child_1: dup2");
        FAILIF(close(pipefd[0]), "child_1: close pipefd");
        execlp("yes", "yes", "abracadabra", NULL);
        FAILIF(1, "child_1: execlp");
    }

    pid_t pid_2 = fork();
    FAILIF(pid_2 < 0, "child_2: fork");
    if (!pid_2) {
        FAILIF(dup2(pipefd[0], 0) == -1, "child_2: dup2");
        FAILIF(close(pipefd[1]), "child_2: close pipefd");
        execlp("head", "head", "-1", NULL);
        FAILIF(1, "child_2: execlp");
    }

    FAILIF(close(pipefd[0]), "close pipefd[0]");
    FAILIF(close(pipefd[1]), "close pipefd[1]");

    int status_1;
    int status_2;
    FAILIF(waitpid(pid_1, &status_1, 0) == -1, "waitpid(child_1)");
    FAILIF(waitpid(pid_2, &status_2, 0) == -1, "waitpid(child_2)");
    describe_child("child_1", status_1);
    describe_child("child_2", status_2);

    return 0;
}

Save to test.c and run with make test && ./test:

abracadabra
child_1 signalled 13
child_2 exited 0
Tantalous answered 15/5, 2019 at 15:34 Comment(4)
make test — you have provided no Makefile.Expiatory
@Shepmaster: Indeed; it’s a built-in implicit rule. Try it! :-)Tantalous
@Stargateur: Shepmaster added that error, not me, but I’ve just edited the post to clarify. No need to get angry.Tantalous
Note that it is a good idea to include your actual error when asking about it.Expiatory
E
10

Use Option::take:

let pipe = child_1.stdout.take().unwrap();

let child_2 = process::Command::new("head")
    .args(&["-n", "1"])
    .stdin(pipe)
    .stdout(process::Stdio::piped())
    .spawn()?;

let output = child_2.wait_with_output()?;
child_1.wait()?;

See also:

Expiatory answered 15/5, 2019 at 15:54 Comment(3)
Thank you, and thanks for the related references! For posterity, fixed Rust Playground link: play.rust-lang.org/….Tantalous
no method named wait found for struct Command in the current scopeUncivil
@AntoninGAVREL you forgot to start the process (e.g. spawn in the example above)Expiatory

© 2022 - 2024 — McMap. All rights reserved.