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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…