gpt4 book ai didi

java - 如何使用 waitFor() 暂停进程

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

我正在尝试从命令行运行 Matlab 脚本,而我又从 Java 调用该脚本。我使用循环多次调用该脚本,并且在每次迭代中我希望我的 Java 程序暂停,直到 Matlab 脚本结束并退出 Matlab。

使用this example (效果很好)作为模板,我想出了以下代码(简化):编辑:增加了输入流和错误流的消耗

Runtime rt = Runtime.getRuntime();
String cmd = "matlab -r \"my_matlab_cmd(arg1, arg2); exit\"";

try {
Process proc = rt.exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while((line = stdInput.readLine()) != null) {
System.out.println(line);
}
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
StringBuilder err = new StringBuilder();
String e = null;
while ((e = stdError.readLine()) != null) {
err.append(e + "\n");
}
if (err.length() != 0) {
throw new IOException(err.toString());
}
int pwf = proc.waitFor();
System.out.println(pwf);
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Matlab finished");

但是,这并不符合预期。 Java 不会等待 Matlab 完成其工作并关闭;相反,它直接进入最终的打印输出命令。没有错误,pwf 的值为 0,正如预期的那样。

我在这里缺少什么?

更新:我刚刚发现,如果我将 toy example 中的 notepad.exe 替换为 matlab.exe ,它不再工作了 - Java 甚至在 Matlab 打开之前就终止了。

最佳答案

Matlab 还需要 -wait 参数才能不立即返回: https://www.mathworks.com/matlabcentral/answers/320908-how-to-start-matlab-from-command-prompt-and-wait-for-the-application-to-return

据我了解,matlab 启动脚本,您可以将其作为子进程传递,因此主 matlab 命令在启动子进程后立即终止,除非您另有说明

另请参阅:https://www.mathworks.com/help/matlab/ref/matlabwindows.html对于无闪屏和其他选项

关于java - 如何使用 waitFor() 暂停进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53908264/

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