【问题标题】:Interrupt std::io::read() in Rust在 Rust 中中断 std::io::read()
【发布时间】:2021-01-07 17:10:28
【问题描述】:

我一直在尝试编写一个在单独的线程中调用系统命令的应用程序。

关键特征是我希望能够终止此命令并根据请求从主线程调用一个新命令

我的辅助线程如下所示:

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 通道通知线程停止)它会等待命令将某些内容输出到标准输出。这是不受欢迎的行为。

我该如何解决这个问题?如何中断 read() 函数?

【问题讨论】:

标签: rust


【解决方案1】:

您可以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();

【讨论】:

  • 非常感谢!没想到
猜你喜欢
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-03
  • 2011-08-11
  • 2023-04-08
  • 2021-07-06
  • 1970-01-01
相关资源
最近更新 更多