16
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rustで外部コマンド実行

Posted at

一行ずつであれば stdout を read_line して stdin に write するコードを書けば良いけど、シェルスクリプトみたいにその辺を気にしたくなければ unsafe を使ってつなげることができる。

use std::process::{Child, Command, Stdio};
use std::os::unix::io::{AsRawFd, FromRawFd};

fn stdout_to_stdin(process: &Child) -> Option<Stdio> {
  if let Some(ref stdout) = process.stdout {
    return Some(unsafe { Stdio::from_raw_fd(stdout.as_raw_fd()) });
  }
  None
}

fn main() {
  let mut process1 = Command::new("bash")
      .arg("-c")
      .arg("while (( i < 100 )); do echo $((i+=1)); done")
      .stdout(Stdio::piped())
      .spawn().expect("failed to run");
  let mut process2 = Command::new("grep")
      .arg("1")
      .stdin(stdout_to_stdin(&process1).expect("broken pipe"))
      .spawn().expect("failed to run");
  process1.wait();
  process2.wait();
}
16
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?