Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

Java Run Command pipe on linux

I am trying to get output of piped command in linux environment but so far no luck.

ProcessBuilder pb = new ProcessBuilder("/bin/sh",  "-c", "top", "-b", "-n", "2", "-d", "0.2", "-p", pid + "", "|",  "tail",  "-1", "|", "awk", "'{print $6}'");
pb.redirectErrorStream(true);
Process p = pb.start();
p.getOutputStream().close();
try (InputStream is = p.getInputStream()) {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        String line = br.readLine();
        System.out.println(line);
    }
}

This outputs: top: failed tty get

When I try that without specifying the script executor (/bin/bash -c): top: unknown option '|'

question from:https://stackoverflow.com/questions/66067403/java-run-command-pipe-on-linux

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The shell command should be a single argument passed after -c. The invoked shell will take care of the piping and tokenization:

ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c",
     "top -b -n 2 -d 0.2 -p " + pid + " | tail -1 | awk '{print $6}'");

For robustness bonus points, pass the variables as separate arguments instead of injecting them into the string (like how you'd use prepared statements in SQL):

ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c",
     "top -b -n 2 -d 0.2 -p "$1" | tail -1 | awk '{print $6}'", "_", String.valueOf(pid));

It makes no difference when pid is an integer, but if it's an arbitrary string, this improves security and robustness.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...