gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:44:48 26 4
gpt4 key购买 nike

我有一个 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 命令的输出。任何帮助将不胜感激。

最佳答案

我不太确定 top 的输出方式,但似乎 top 没有将其结果发送到 STDOUT正常的方式。

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

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

关于java - 如何将shell脚本输出重定向到java控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24806570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com