Java exec() does not return expected result of pipes' connected commands

后端 未结 6 573
傲寒
傲寒 2020-12-11 05:58

I\'m calling command line programs connected by pipes. All this works on Linux for sure.

My method:

protected String execCommand(String command) thro         


        
6条回答
  •  感动是毒
    2020-12-11 06:25

    The pipe (like redirection, or >) is a function of the shell, and so execing directly from Java won't work. You need to do something like:

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

    which executes a shell process with the command line (including pipes) specified after the -c (in quotes).

    Note also that you have to consume stdout and stderr concurrently, otherwise your spawned process will block waiting for your process to consume the output (or errors). More info here.

提交回复
热议问题