如何将shell脚本输出重定向到java控制台

时间:2014-07-17 14:40:00

标签: java shell

我有一个shell脚本,它将输出发送到控制台

ID=$PPID
echo the process id of the parent of this script is $ID

#fetch the parent of the program which executed this shell
read PID < <(exec ps -o ppid= "$ID")
echo the grand parent id of the script is $PID

read GPID < <(exec ps -o ppid= "$PID")
echo the grand parent id of the script is $GPID


while read -u 4 P; do
 top -c -n 1 -p "$P"
done 4< <(exec pgrep -P "$PID") >&1

我从java程序调用此脚本并尝试在控制台上显示输出,但只显示echo的输出。 top命令的输出没有出现在java控制台上。

这是我的java程序

import java.io.BufferedReader;

public class InformationFetcher {

    public InformationFetcher() {
    }

    public static void main(String[] args) {
    InformationFetcher informationFetcher = new InformationFetcher();
    try {
        Process process = Runtime.getRuntime().exec(
            informationFetcher.getFilePath());
        InputStream in = process.getInputStream();
        printInputStream(in);
    } catch (IOException e) {
        e.printStackTrace();
    }

    }

    private static void printInputStream(InputStream in) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuffer outBuffer = new StringBuffer();
    String newLine = System.getProperty("line.separator");
    String line;
    while ((line = reader.readLine()) != null) {
        outBuffer.append(line);
        outBuffer.append(newLine);
    }
    System.out.println(outBuffer.toString());
    }

    public String getFilePath() {
    return this.getClass().getResource("/idFetcher.sh").getPath();
    }

}

输出

the process id of the parent of this script is 3721
the grand parent id of the script is 3241
the grand parent id of the script is 3240

但它也应该显示top命令的输出。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我对top输出的方式不太确定,但似乎top没有以正常方式将结果发送到STDOUT。< / p>

但是,如果您希望top以正常方式将结果发送到STDOUT,请为其指定-b

top -b -n 1
# -b means in batch mode, which outputs to `STDOUT` normally