I'm doing a challenge where a linux executable outputs to stdout a simple expression that I need to solve and send back the answer to its stdin under a certain time constraint.
Running the program shows something like this:
Challenge: 1+1
Setting alarm...
Solution?
Note that there is no newline \n after ? .
For this I am using std::process::Command::spawn():
let mut child = Command::new(program)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
match (child.stdin.as_mut(), child.stdout.as_mut()) {
(Some(stdin), Some(stdout)) => {
// 1) Read from subprocess' stdout
// 2) Evaluate
// 3) Write to subprocess' stdin
// 4) Read from subprocess' stdout
}
_ => panic!("Could not get stdin or stdout"),
}
Unfortunately I cannot achieve the steps:
- Read from subprocess' stdout
- Evaluate
- Write to subprocess' stdin
- Read from subprocess' stdout
First issue: if I don't wrap the stdin into a BufWriter I get a Broken pipe with write!(stdin, "{}", answer).unwrap();. Is that normal?
After using the BufWriter I get to step 4. But then everything fails...
If I try to read one byte at a time, I only get the first two lines of step 1. I cannot get the Solution? . If I run unbuffer instead and move program to Command's arg(), I can read up to the Solution? . But in both cases, there isn't anything left in stdout!
I know that the program should outputs something. Timing the whole execution is around 50 ms, and the program times out after 200 ms (with SIGALARM). In that case the program should reply success or failure based on the answer.
All this tells me there is something fishy with buffers:
-
stdinneeded to be wrapped in aBufWriter - Using
unbufferallows me to read (one byte at a time) until the last character of step 1. - It's as if the program never received my input and just exited.
Does anyone would have a clue as to how I can solve this??
Thanks!!