Larry Larry - 13 days ago 8
Java Question

Getting command Input with runtime java

Hello i try to get Input in java from this command: "ps aux | grep java"
I use this code but not work:

Process process = Runtime.getRuntime().exec("ps aux | grep java");
InputStream stdin = process.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);

String line = null;
System.out.println("<OUTPUT>");

while ((line = br.readLine()) != null) {
System.out.println(line);
}

System.out.println("</OUTPUT>");
int exitVal = process.waitFor();
System.out.println("Process exitValue: " + exitVal);


output in console:


Process exitValue: 1
Any ideas?

Answer

When you pass a single string to Runtime.getRuntime().exec(), it expects a single command and its arguments, which are automatically tokenized. In other words, your code is equivalent to executing this command:

ps 'aux' '|' 'grep' 'java'

See how |, grep, and java are all being passed as arguments to ps? That's the problem.

I suggest using ProcessBuilder instead, and running your command via bash:

Process process = new ProcessBuilder().command("bash", "-c", "ps aux | grep java").start()

This is equivalent to the following command:

bash -c 'ps aux | grep java'

Now the bash subprocess handles the piping between ps and grep, so it should all work correctly.

You could do the same thing with Runtime.getRuntime().exec(), but ProcessBuilder is a newer, cleaner interface and thus should probably be preferred for new code. (ProcessBuilder is actually just relatively new, since it was added in JDK1.5, vs the exec() method being around since JDK1.0.)