Subprocess Error

I noticed an odd error with running sub-processes. If I run the following I get the desired output from the local machine:

fn main() {
  use std::process::Command;

  let mut list_dir = Command::new("date");
  list_dir.status().expect("process failed to execute");

  println!();
}

$ ./target/release/system 
Wed 29 Jul 2020 04:28:05 AM CDT

Yet if I change it to this I get an error:

fn main() {
  use std::process::Command;

  let mut list_dir = Command::new("ssh -T user@192.168.x.x 'date'");
  list_dir.status().expect("process failed to execute");

  println!();
}

$ ./target/release/system 
thread 'main' panicked at 'process failed to execute: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:7:3
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

I tried running RUST_BACKTRACE=1, but I didn't get any new output upon re-running this.

I should note that I've confirmed SSH works without a password. I doubt it matters, but I'm doing this between two Linux devices. Any suggestions?

Because in the second example you're not executing ssh, but a program named ssh -T user@192.168.x.x 'date', which obviously not exist in your system. Normally program name and its arguments are separated by your shell program, like bash or zsh. But with std::process::Command there's no shell by default so you should separate the arguments by your hand via Command::arg() or Command::args(). Command in std::process - Rust

fn main() {
  use std::process::Command;

  let mut list_dir = Command::new("ssh");
  list_dir.args(&["-T", "user@192.168.x.x", "date"]);
  list_dir.status().expect("process failed to execute");

  println!();
}
2 Likes

That works perfect and makes sense from other languages I've seen. The list_dir.args wasn't in the documentation I read. Thank you!

For reference - here it is in the current std docs.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.