首页 > 解决方案 > 如何在 Rust 中杀死 Ctrl+C 事件的进程?

问题描述

我正在尝试Ctrl+C使用ctrlc包覆盖该事件。我想在事件中杀死一个子进程。我目前正在这样做。

let mut child = Command::new(shell)
    .arg(option)
    .arg(script)
    .spawn()
    .unwrap();

ctrlc::set_handler(move || {
    println!("Received Ctrl+C!");
    child.kill().expect("Couldn't kill the process!");
})
.expect("Error setting interrupt handler!");

child.wait().unwrap();

但我有错误cannot borrow child as mutable, as it is a captured variable in a Fn closure。错误的含义是什么,我该如何解决?

标签: rust

解决方案


set_handler启动“一个新的专用信号处理线程”。

似乎set_handlerexpects Fn,与此相反FnMut- 不能被突变。因为它不能变异,所以它不能变异捕获的child.

您可以尝试child在闭包内定义并与外线程通信。

您可以尝试在线程之间建立通信(例如使用mpsc::channel),而不是在主线程中使用waitfor 。child您可以尝试检索stdout / stderr而不是waiting。


推荐阅读