Java exec() 不返回管道连接命令的预期结果 [英] Java exec() does not return expected result of pipes' connected commands

查看:35
本文介绍了Java exec() 不返回管道连接命令的预期结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用由管道连接的命令行程序.所有这些都可以在 Linux 上运行.

I'm calling command line programs connected by pipes. All this works on Linux for sure.

我的方法:

protected String execCommand(String command) throws IOException {
    String line = null;
    if (command.length() > 0) {
        Process child = Runtime.getRuntime().exec(command);
        InputStream lsOut = child.getInputStream();
        InputStreamReader r = new InputStreamReader(lsOut);
        BufferedReader in = new BufferedReader(r);

        String readline = null;
        while ((readline = in.readLine()) != null) {
            line = line + readline;
        }
    }

    return line;
}

如果我正在调用一些 cat 文件 |grep asd,我得到了预期的结果.但并非所有命令都能正常工作.例如:

If I'm calling some cat file | grep asd, I'm getting the expected result. But not all commands works correctly. For example with this:

cat /proc/cpuinfo | wc -l

或者这个:

cat /proc/cpuinfo | grep "model name" | head -n 1 | awk -F":" '{print substr($2, 2, length($2))}

该方法将返回空值.我猜这个问题取决于输出格式命令,如 headtailwc 等.我如何解决这个问题并得到输出的最终结果?

the method will return null. I'm guessing this problem depends on output formatting commands like head, tail, wc, etc. How I can work around this problem and get the final result of the output?

推荐答案

仍然没有找到使用 Runtime.exec 执行管道命令的正确解决方案,但找到了解决方法.我只是编写了这些脚本来分隔 bash 文件.然后 Runtime.exec 调用这些 bash 脚本并得到预期的结果.

Still didn't found proper solution to execute piped commands with Runtime.exec, but found a workaround. I've simply wrote these scripts to separate bash files. Then Runtime.exec calls these bash scripts and gets expected result.

这篇关于Java exec() 不返回管道连接命令的预期结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆