【问题标题】:Java Runtime Process Won't "Grep"Java 运行时进程不会“Grep”
【发布时间】:2011-10-19 17:53:20
【问题描述】:

我正在我的 java 程序中从命令行执行一些命令,但它似乎不允许我使用“grep”?我已经通过删除“grep”部分对此进行了测试,并且命令运行得很好!

我的代码不起作用:

String serviceL = "someService";
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("chkconfig --list | grep " + serviceL);

有效的代码:

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("chkconfig --list");

这是为什么?是否有某种正确的方法或解决方法?我知道我可以只解析整个输出,但我会发现从命令行完成这一切更容易。谢谢。

【问题讨论】:

    标签: java linux process runtime grep


    【解决方案1】:

    管道(如重定向,或>)是shell 的一个功能,因此直接从Java 执行它是行不通的。您需要执行以下操作:

    /bin/sh -c "your | piped | commands | here"
    

    -c(引号)之后指定的命令行(包括管道)内执行一个shell进程。

    所以,这是一个适用于我的 Linux 操作系统的示例代码。

    public static void main(String[] args) throws IOException {
        Runtime rt = Runtime.getRuntime();
        String[] cmd = { "/bin/sh", "-c", "ps aux | grep skype" };
        Process proc = rt.exec(cmd);
        BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line;
        while ((line = is.readLine()) != null) {
            System.out.println(line);
        }
    }
    

    在这里,我正在提取我所有的“Skype”进程并打印进程输入流的内容。

    【讨论】:

      【解决方案2】:

      您正在尝试使用作为 shell 的功能的管道......并且您没有使用 shell;您正在直接执行chkconfig 进程。

      简单的解决方案是执行 shell 并让它做所有事情:

      Process proc = rt.exec("/bin/sh -c chkconfig --list | grep " + serviceL);
      

      话虽这么说......你为什么要管道到grep?只需阅读chkconfig 的输出并在java 中自己进行匹配。

      【讨论】:

      • 没有理由我不能在 Java 中匹配。我只是认为写出 grep 比解析输出要快。我对 Linux 比较陌生,所以我不知道 grep 是 shell 的一个功能。谢谢!
      • @Max: grep 不是 shell 内置函数,管道 | 是 shell 语法特性。
      【解决方案3】:

      String[] commands = { "bash", "-c", "chkconfig --list | grep " + serviceL }; 进程 p = Runtime.getRuntime().exec(commands);

      或者如果你在 linux 环境中,只需使用 grep4j

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-26
        • 2013-08-09
        • 2013-02-22
        • 1970-01-01
        • 1970-01-01
        • 2015-12-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多