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

如何在RootTools/RootShell中执行命令并发送SIGINT终止进程?

解决RootTools下运行二进制并发送SIGINT的问题

我来帮你搞定这个RootTools的难题,结合你需要读取标准输出的核心需求,这里有几个实用的方案:

方案1:用Shell语法组合命令(同一会话完成操作)

RootTools虽然一次只能打开一个shell,但我们可以把两条逻辑用Shell的后台运行+PID捕获语法整合成一条命令,这样就能在同一个shell会话里完成启动、等待、发送信号的操作,同时还能通过RootTools捕获输出。

示例命令如下(根据你的实际二进制路径和需求调整):

./path/to/your_binary & PID=$!; sleep 3; kill -SIGINT $PID
  • ./path/to/your_binary &:把二进制进程放到后台运行,不阻塞当前shell
  • PID=$!:捕获后台进程的PID
  • sleep 3:等待进程运行足够时间(你可以根据实际情况调整时长,或者去掉这步换成其他判断逻辑)
  • kill -SIGINT $PID:向目标进程发送SIGINT信号终止它

然后用RootTools执行这条组合命令,就能同时捕获二进制的输出并完成终止操作:

RootTools.getShell(true).add(new Command(0, "./path/to/your_binary & PID=$!; sleep 3; kill -SIGINT $PID") {
    @Override
    public void onOutput(int id, String line) {
        // 这里处理二进制输出的每一行内容
        System.out.println("输出:" + line);
        super.onOutput(id, line);
    }

    @Override
    public void onCompleted(int id, int exitCode) {
        // 命令执行完成后的回调
        super.onCompleted(id, exitCode);
    }
});

如果担心后台进程的输出捕获不完整,可以把输出重定向到临时文件,最后再读取文件内容:

./path/to/your_binary > /tmp/binary_output.log & PID=$!; sleep 3; kill -SIGINT $PID; cat /tmp/binary_output.log

这样RootTools就能通过cat命令的输出拿到二进制的完整日志。

方案2:使用持久化Shell分步骤执行

RootTools支持创建持久化的shell会话,你可以先发送启动命令,再根据需要(比如等待特定输出、延迟一段时间)发送终止命令,这种方式更灵活。

示例代码:

// 获取持久化的root shell
Shell persistentShell = RootTools.getShell(true);

// 第一步:启动二进制进程(后台运行)
persistentShell.add(new Command(1, "./path/to/your_binary &") {
    @Override
    public void onOutput(int id, String line) {
        // 实时处理二进制的输出
        System.out.println("实时输出:" + line);
        
        // 可选:如果需要根据特定输出触发终止,可以在这里判断
        if (line.contains("特定关键词")) {
            // 发送终止命令
            persistentShell.add(new Command(2, "kill -SIGINT $(pgrep your_binary)"));
        }
        super.onOutput(id, line);
    }
});

// 第二步:延迟一段时间后发送终止信号(如果不需要根据输出判断)
new Thread(() -> {
    try {
        Thread.sleep(3000); // 等待3秒
        // 通过进程名获取PID并发送SIGINT
        persistentShell.add(new Command(2, "kill -SIGINT $(pgrep your_binary)"));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}).start();

这里用pgrep your_binary获取进程PID,如果你的二进制有重名进程,建议用更精准的方式(比如结合启动路径过滤):pgrep -f "./path/to/your_binary"

方案3:直接通过RootTools执行kill命令(已知PID时)

如果你能通过其他方式拿到二进制进程的PID(比如启动时记录到文件),可以直接用RootTools执行kill命令发送SIGINT:

String targetPid = "12345"; // 替换为实际PID
RootTools.getShell(true).add(new Command(0, "kill -SIGINT " + targetPid));

补充说明

RootTools本身没有原生的发送信号API,所以核心思路还是通过执行Shell的kill命令来实现,但通过以上几种方式,既满足了RootTools读取标准输出的需求,又能完成发送SIGINT的操作。

内容的提问来源于stack exchange,提问作者superl2

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:38:41