gpt4 book ai didi

java - 从 Java 执行 shell 命令

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:48:04 28 4
gpt4 key购买 nike

我正在尝试从 GNU/Linux 平台上的 java 应用程序执行 shell 命令。问题是调用另一个 java 应用程序的脚本永远不会结束,尽管它从 bash 成功运行。我试着调试它:

(gdb) bt#0  0xb773d422 in __kernel_vsyscall ()#1  0xb7709b5d in pthread_join (threadid=3063909232, thread_return=0xbf9cb678) at pthread_join.c:89#2  0x0804dd78 in ContinueInNewThread ()#3  0x080497f6 in main ()

我试过:ProcessBuilder();和 Runtime.getRuntime().exec(cmd);

看起来它在等待某事完成。有什么想法吗?

谢谢,劳伦斯修

最佳答案

您是否正在处理标准输入和标准输出?来自javadocs :

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

Process cmdProc = Runtime.getRuntime().exec(command);


BufferedReader stdoutReader = new BufferedReader(
new InputStreamReader(cmdProc.getInputStream()));
String line;
while ((line = stdoutReader.readLine()) != null) {
// process procs standard output here
}

BufferedReader stderrReader = new BufferedReader(
new InputStreamReader(cmdProc.getErrorStream()));
while ((line = stderrReader.readLine()) != null) {
// process procs standard error here
}

int retValue = cmdProc.exitValue();

关于java - 从 Java 执行 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3062305/

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