How to kill a spawned process from a reading thread?

I have a code like:

let mut child = Command::new(&path_translated)
         .stdout(Stdio::piped())
         .stdin(Stdio::piped())
         .stderr(Stdio::piped())
         .spawn()?;
....
 if let Some(mut stdin) = child.stdin.take() { 
         
       thread::scope(|s| {
            s.spawn(|| {
....
     child.kill().expect("Failed to kill child process");
          }
  if let Some(stderr)  = child.stderr.take() {
             s.spawn(|| {

Since child got moved in the first thread, I can't use it for taking stderr. How can I clone the child, or there is an another technique?

Do the take()s first, before the move happens. Also, there's no point in using if let because the Options will always be Some — using unwrap() instead will simplify the code and remove the appearance of handling impossible cases.

let mut child = Command::new(&path_translated)
     .stdout(Stdio::piped())
     .stdin(Stdio::piped())
     .stderr(Stdio::piped())
     .spawn()?;

let stdin = child.stdin.take().unwrap();
let stderr = child.stderr.take().unwrap();
         
thread::scope(|s| {
    s.spawn(|| {
        // ... write stdin
        child.kill().expect("Failed to kill child process");
    });
    s.spawn(|| {
        // ... read stderr
    });
});
1 Like

Thanks, it looks like a good suggestion.

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.