You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中使用kill()无法终止子进程的问题求助

Rust中使用kill()无法终止子进程的问题求助

我实现了一个名为execute_command的函数,用来处理像ping <ip> -t这类会无限运行的命令。原本想在子进程运行超过20秒时,调用.kill()来终止它,但实际测试发现,即使触发了超时逻辑,子进程依然会在终端里继续运行——比如执行ping命令时,还一直在输出Reply from 192.168.31.7: bytes=32 time<1ms TTL=128这类信息。

这到底是哪里出问题了?有没有其他可靠的方式实现这个超时终止的需求?

我的代码如下:

use std::process::Command;
use tokio::time::{sleep, Duration, Instant};

async fn execute_command(command: &str) -> Result<String, std::io::Error> {

    let mut child = Command::new("powershell")
        .arg("-Command")
        .arg(command)
        .spawn()?;
    
    let start = Instant::now();
    loop {
        // Check if the process has completed
        match child.try_wait()? {
            Some(_) => {
                let output = child.wait_with_output()?;
                let response_text = String::from_utf8_lossy(&output.stdout).to_string();
                return Ok(response_text)
            }
            None => {
                // Process hasn't completed yet, check if timeout has elapsed
                if start.elapsed() >= Duration::from_secs(20) {
                    child.kill()?;
                    return Ok("Failed to execute command: TimeOut".to_owned())
                } else {
                    // Wait a bit before trying again to avoid busy-waiting
                    sleep(Duration::from_millis(100)).await;
                }
            }
        }
    }    
}

备注:内容来源于stack exchange,提问作者clark jsold

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 10:13:11