Hi everyone, I am new to the language and trying to learn by doing some exersices.
I have a programA that continously writes to stdout lines and I want to pipe it to the stdin of my programB, process the line and write it to stdout. I do not have control over programA. When I try to use stdout my program panics with "Broken pipe (os error 32)" error.
fn main() {
let stdin = io::stdin();
let mut stdout = io::stdout().lock();
let mut traces_by_id: HashMap<String, Trace> = HashMap::new();
let mut identified_traces: Vec<Trace> = vec![];
let mut buffer: Vec<String> = vec![];
for line in stdin.lock().lines() {
match line {
Ok(ln) => {
buffer.push(ln);
if buffer.len() >= 10000 {
for ln in buffer.drain(..) {
let new_identified_traces = prune_old_traces(&mut traces_by_id);
identified_traces.extend(new_identified_traces);
// Use the parse_line function to parse the read line
if let Some(log_entry) = parse_line(&ln) {
let trace_id = &log_entry.trace_id;
match traces_by_id.entry(trace_id.clone()) {
std::collections::hash_map::Entry::Vacant(e) => {
let trace = Trace {
trace_id: trace_id.clone(),
log_entries: vec![log_entry.clone()],
lines_since_last_found: 0,
};
e.insert(trace);
}
std::collections::hash_map::Entry::Occupied(mut e) => {
e.get_mut().lines_since_last_found = 0;
e.get_mut().log_entries.push(log_entry.clone());
}
}
}
for trace in identified_traces.clone() {
if let Some(t) = construct_tree(trace) {
let output = format!("{:?}\n", t);
match stdout.write_all(output.as_bytes()) {
Ok(_) => {}, // Write was successful, do nothing
Err(e) => {
eprintln!("Error writing to stdout: {}", e);
continue; // Skip the current iteration and move on to the next line
}
}
}
}
}
}
}
Err(_) => {
eprintln!("Error reading line");
}
}
}
}
How can I write to stdout without causing panic?