I am trying to create a shell and then to execute commands within that process. The code compiles and executes but I get s empty string both from stdout and stderr and don’t know why. already tried to debug but nothing, dont know what else to do.
pub struct Shell {
child: Child,
stdin: ChildStdin,
stdout: ChildStdout,
stderr: ChildStderr,
}
impl Shell {
pub fn new() -> Result<Shell, io::Error> {
#[cfg(unix)]
let shell = "sh";
#[cfg(unix)]
let shell_arg = "-c";
#[cfg(windows)]
let shell = "cmd";
#[cfg(windows)]
let shell_arg = "/C";
let mut cmd = Command::new(shell);
cmd.arg(shell_arg)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = cmd.spawn()?;
let stdin = child.stdin.take().ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Failed to open stdin"))?;
let stdout = child.stdout.take().ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Failed to open stdout"))?;
let stderr = child.stderr.take().ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Failed to open stderr"))?;
Ok(Shell { child, stdin, stdout, stderr })
}
pub fn execute(&mut self, command: &str) -> Result<(String, String), io::Error> {
writeln!(self.stdin, "{}", command)?;
let mut stdout_buf = String::new();
let mut stderr_buf = String::new();
let mut stdout_reader = BufReader::new(&mut self.stdout);
println!("test: {:?}", stdout_reader);
let mut stderr_reader = BufReader::new(&mut self.stderr);
stdout_reader.read_to_string(&mut stdout_buf)?; // Read from stdout
stderr_reader.read_to_string(&mut stderr_buf)?; // Read from stderr
Ok((stdout_buf, stderr_buf))
}
pub fn close(&mut self) -> Result<(), io::Error> {
self.child.kill()?;
self.child.wait()?;
Ok(())
}
}
New contributor
Mario Portilho is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.