How to Make Pipes Work With Runtime.Exec()

How to make pipes work with Runtime.exec()?

Write a script, and execute the script instead of separate commands.

Pipe is a part of the shell, so you can also do something like this:

String[] cmd = {
"/bin/sh",
"-c",
"ls /etc | grep release"
};

Process p = Runtime.getRuntime().exec(cmd);

How to use pipes in a java Runtime.exec

To get the shell commands like |, use /bin/bash as your first argument to exec, -c as the second, and the entire string (including find, it's parameters and the pipe etc) as the third.

Process result = Runtime.getRuntime().exec(new String[]{"/bin/bash", "-c", "/usr/bin/find " + baseDir+"/.. -type f | /usr/bin/grep " +filter1 + "| /usr/bin/grep "+filter2+" | /usr/bin/wc -l"});

How to use Pipe Symbol 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 a Matcher and only pay attention to the lines that include java from your InputStream

http://download.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html

Java and exec command - pipe multiple commands

Try this:

String[] COMPOSED_COMMAND = {
"/bin/bash",
"-c",
"/usr/bin/openssl rand -base64 8 | tr -d '+' | cut -c1-8",};
Process p = Runtime.getRuntime().exec(COMPOSED_COMMAND);

Creating a named pipe in Java with exec calls

If you write out the third argument, you'll get this:

"mkfifo ~/myFifo && tail -f ~/myFifo | csh -s"

And if you try to run that in a shell, you'll see that it doesn't work:

$ "mkfifo ~/myFifo && tail -f ~/myFifo | csh -s"
bash: mkfifo ~/myFifo && tail -f ~/myFifo | csh -s: No such file or directory

Just remove the literal quotes you added:

final String [] cmds = {"/bin/sh", "-c", "mkfifo ~/myFifo && tail -f ~/myFifo | csh -s"};

and remember to read from the Process.getInputStream().

How to make Pipe symbol or Grep work in an Android process runtime command?

Other answers on this website were not very clear. Here is the solution.
You need to append "/system/bin/sh -c" before your runtime command for grep to work.
Cheers.



Related Topics



Leave a reply



Submit