Java exec() does not return the expected result of the pipe connect command

I'm calling a command line program connected through a pipe All of these can run on Linux

My approach:

protected String execCommand(String command) throws IOException {
    String line = null;
    if (command.length() > 0) {
        Process child = Runtime.getRuntime().exec(command);
        InputStream lsOut = child.getInputStream();
        InputStreamReader r = new InputStreamReader(lsOut);
        BufferedReader in = new BufferedReader(r);

        String readline = null;
        while ((readline = in.readLine()) != null) {
            line = line + readline;
        }
    }

    return line;
}

If I'm calling some cat files | grep ASD, I get the expected results But not all commands work properly For example:

cat /proc/cpuinfo | wc -l

Or this:

cat /proc/cpuinfo | grep "model name" | head -n 1 | awk -F":" '{print substr($2,2,length($2))}

This method will return null I guess this problem depends on the output formatting commands, such as head, tail, WC, etc How do I solve this problem and get the final result of the output?

Solution

Pipes (such as redirection or >) are a function of the shell, so executing directly from Java will not work You need to do something:

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

It executes the shell process using the command line (including the pipe) specified after - C (quotation marks)

Also note that you must use stdout and stderr at the same time, otherwise the process you build will prevent the process waiting for you from using output (or errors) More information here

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>