gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:36:29 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com