中断Rust中的std::io::read()



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

关键特性是,我希望能够终止此命令,并在请求时从主线程调用一个新命令

我的次要线程看起来是这样的:

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通道通知线程停止(,它会等待命令向stdout输出一些内容这是不必要的行为。

我该如何补救?如何中断read((函数?

您可以终止子进程,这将导致它关闭输出,此时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();

相关内容

最新更新