I am using the following code to get the details of all process running in the system:
Process p = Runtime.getRuntime().exec("ps aux");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
I want to filter ps aux down with the pipe symbol so I use this:
Process p = Runtime.getRuntime().exec("ps aux | grep java");
It goes to the ErrorStream. Later I noticed the Pipe Symbol (|) is used as Bitwise inclusive OR operator in Java. So I used backslash in front of pipe symbol as shown below:
Process p = Runtime.getRuntime().exec("ps aux \\| grep java");
But again it goes to the ErrorStream. How can I run ps aux | grep java through exec in Java?
The pipe is a shell feature – you’re not using a shell, you’re exec’ing a process (
ps).But really, why would you want to do this? What you’re saying is:
“execute ps, then pipe its output to another program (grep) and have it extract what I need”
You just need to extract what you want from the output of
ps. Use aMatcherand only pay attention to the lines that includejavafrom yourInputStreamhttp://download.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html