threads_callback/threads_callback.rs
1use r2pipe::{R2Pipe, Result};
2use std::sync::Arc;
3
4fn main() -> Result<()> {
5 // First we define a callback. It doesn't block and gets called after a thread receives output from r2pipe
6 // Note: First argument to the callback is the thread id, second one the r2pipe output
7 let callback = Arc::new(|id, result| {
8 println!("Pipe #{} says: {}", id, result);
9 });
10
11 // First two arguments for R2Pipe::threads() are the same as for R2Pipe::spawn() but inside vectors
12 // Third and last argument is an option to a callback function
13 // The callback function takes two Arguments: Thread ID and r2pipe output
14 let pipes = match R2Pipe::threads(
15 vec!["/bin/ls", "/bin/id", "/bin/cat"],
16 vec![None, None, None],
17 Some(callback),
18 ) {
19 Ok(p) => p,
20 Err(e) => {
21 println!("Error spawning Pipes: {}", e);
22 return Ok(());
23 }
24 };
25
26 // At this point we can iter through all of our r2pipes and send some commands
27 for p in pipes.iter() {
28 if let Ok(_) = p.send("ij".to_string()) {};
29 }
30
31 // Meanwhile: Expecting callbacks
32 std::thread::sleep(std::time::Duration::from_millis(1000));
33
34 // Finally properly close all pipes
35 // Note: For "join()" we need to borrow so pipes.iter() won't work for this
36 for p in pipes {
37 if let Ok(_) = p.send("q".to_string()) {};
38 p.handle.join().unwrap()?;
39 }
40
41 Ok(())
42}