Java运行时进程不会"Grep"

Max*_*Max 5 java linux grep runtime process

我正在java程序中从命令行执行一些命令,看来它不允许我使用"grep"?我通过删除"grep"部分测试了这个,命令运行得很好!

我的代码不起作用:

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

有效的代码:

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("chkconfig --list");
Run Code Online (Sandbox Code Playgroud)

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

Kon*_*kov 8

管道(如重定向或>)是shell的一个功能,因此直接从Java执行它将不起作用.你需要做一些事情:

/bin/sh -c "your | piped | commands | here"
Run Code Online (Sandbox Code Playgroud)

它在-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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我将提取所有"Skype"进程并打印进程输入流的内容.


Bri*_*ach 6

你正在尝试使用管道,这是外壳的一个功能...你没有使用外壳; 你chkconfig直接执行这个过程.

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

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

那就是说......为什么你要用油管吹?只需阅读输出chkconfig并在java中自己进行匹配.

  • @Max:grep不是shell内置的,管道`|`是shell语法功能. (3认同)