简体   繁体   English

Java运行时进程不会“Grep”

[英]Java Runtime Process Won't “Grep”

I'm executing some commands from the command line in my java program, and it appears that it doesn't allow me to use "grep"? 我正在java程序中从命令行执行一些命令,看来它不允许我使用“grep”? I've tested this by removing the "grep" portion and the command runs just fine! 我通过删除“grep”部分测试了这个,命令运行得很好!

My code that DOESN'T work: 我的代码不起作用:

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

Code that does work: 有效的代码:

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

Why is this? 为什么是这样? And is there some sort of correct method or workaround? 是否有某种正确的方法或解决方法? I'm aware that I could just parse the entire output, but I would find it easier to do it all from the command line. 我知道我可以解析整个输出,但我会发现从命令行更容易完成。 Thanks. 谢谢。

The pipe (like redirection, or > ) is a function of the shell, and so executing it directly from Java won't work. 管道(如重定向或> )是shell的一个功能,因此直接从Java执行它将不起作用。 You need to do something like: 你需要做一些事情:

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

which executes a shell process within the command line (including pipes) specified after the -c (in quotes). 它在-c (引号)后指定的命令行(包括管道)中执行shell进程。

So, here's is a sample code that works on my Linux OS. 所以,这是一个适用于我的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);
    }
}

Here, I'm extracting all my 'Skype' processes and print the content of the process input stream. 在这里,我将提取所有“Skype”进程并打印进程输入流的内容。

You're trying to use piping which is a function of the shell ... and you're not using a shell; 你正在尝试使用管道,这是外壳的一个功能...你没有使用外壳; you're exec'ing the chkconfig process directly. 你直接执行chkconfig过程。

The easy solution would be to exec the shell and have it do everything: 简单的解决方案是执行shell并让它完成所有事情:

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

That being said ... why are you piping to grep? 那就是说......为什么你要用油管吹? Just read the output of chkconfig and do the matching yourself in java. 只需阅读chkconfig的输出并在java中自己进行匹配。

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

or if you are in a linux env just use grep4j 或者如果你在Linux环境中,只需使用grep4j

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM