Runtime.exec() and the Pipe Operator

In a recent Java project, we needed to use Runtime.exec() to execute a command in a separate process. And we needed to read the output and work with it. Our reusable code worked perfectly with almost all the commands that we needed to run. Almost…

The code that executed a given command called theCommand looked like this:

Process process = Runtime.getRuntime().exec(theCommand);
BufferedInputStream is = new BufferedInputStream(process.getInputStream());

As I mentioned above, this worked with all the commands but one. The “ps -ef | grep xxx” command failed to generate the output that we expected. The reason, that we discovered shortly after, is that operators like pipes ( | ) are shell features, however the command string passed to exec() isn’t executed in a shell. To do so, we had to invoke the shell explicitly. The following code solved the problem:

Process process = Runtime.getRuntime().exec(new String[]{"sh", "-c", theCommand});
BufferedInputStream is = new BufferedInputStream(process.getInputStream());

– Yagiz –

, , , ,

  1. #1 by blop on February 27, 2009 - 3:11 pm

    What does the -c do?

  2. #2 by Yagiz Erkan on March 2, 2009 - 3:14 pm

    sh -c … command_string [command_name [argument…]]

    Read commands from the command_string operand…

  3. #3 by Silvermage on October 30, 2009 - 6:20 am

    Thanks Yagiz, you just saved my day 🙂

  4. #4 by Carlos on November 1, 2009 - 11:40 am

    This article rocks… It saved a lot of pain in my project. Thanks Yagiz

  5. #5 by Arun on December 5, 2009 - 2:16 am

    Thanks… I was wondering why commands with pipe were crashing…

  6. #6 by Raj on January 21, 2011 - 7:03 pm

    Thanks…I just stumbled on same issue running piped commands in exec(). Appreciate documenting this issue and solution, it is very helpful. You saved my day!

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: