rust - 在Rust中中断std::io::read()

标签 rust

我一直试图编写一个在单独的线程中调用系统命令的应用程序。
关键特征是我希望能够终止该命令,并根据请求从主线程调用一个新命令。
我的辅助线程如下所示:

let (tx, rx): (mpsc::Sender<String>, mpsc::Receiver<String>) = mpsc::channel();

let child_handle = stoppable_thread::spawn(move |stop| {
  let mut child = Command::new("[the program]").arg(format!("-g {}", gain)).stdout(Stdio::piped()).spawn().expect("naw man");
  let mut childout = child.stdout.as_mut().unwrap();
  while !stop.get() {
    let mut buffer = [0; 128];
    childout.try_read(&mut buffer).unwrap(); // This part makes the code wait for the next output
    // Here the buffer is sent via mpsc irrelevant to the issue
}});
问题是当我发送停止信号(或者如果我使用mpsc channel 通知线程停止)时,它将等待命令向stdout输出内容。 这是有害行为。
我该如何补救?如何中断read()函数?

最佳答案

您可以kill子进程,这将导致它关闭其输出,此时read将看到一个EOF并返回。但是,这需要将子级发送到父线程。就像是:

let (tx, rx): (mpsc::Sender<String>, mpsc::Receiver<String>) = mpsc::channel();
let (ctx, crx) = mpsc::channel();

let child_handle = stoppable_thread::spawn(move |stop| {
  let mut child = Command::new("[the program]").arg(format!("-g {}", gain)).stdout(Stdio::piped()).spawn().expect("naw man");
  let mut childout = child.stdout.take().unwrap();
  ctx.send (child);
  while !stop.get() {
    let mut buffer = [0; 128];
    childout.try_read(&mut buffer).unwrap(); // This part makes the code wait for the next output
    // Here the buffer is sent via mpsc irrelevant to the issue
}});

// When you want to stop:
let child = crx.recv().unwrap();
child.kill().unwrap();

关于rust - 在Rust中中断std::io::read(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65616915/

相关文章:

rust - 如何使用rust "use another-file"?带有连字符的模块

stream - 使用 PhantomData 和 unsafe 将流式迭代器作为普通迭代器处理

vector - 如何反向填充向量?

rust - 基于 lambda 的迭代器的生命周期

rust - 向量借用和所有权

rust - 无法分配给结构字段,因为它已被借用,但借用的字段在单独的范围内

rust - 发生移动是因为 `*arg` 的类型为 `String` ,该类型未实现 `Copy` 特征

generics - 满足与 const 泛型表达式绑定(bind)的特征,这可能吗?

vector - 读取 2D 矢量时如何消除临时矢量?

opengl - 从三角形创建圆圈还是使用片段着色器绘制它们更快?