如何通过 JAVA 测试我的脚本 sh 是否仍然是 运行

How to test if my script sh is still running by JAVA

我有一个 java class 运行 多个 shell 循环脚本,如下所示:

for (int i = 0; i < list.size(); i++) {
Runtime.getRuntime().exec(file.getAbsolutePath() + "/script.sh");
}

在同一个 class 中,3 分钟后我想测试脚本 sh 是否仍在 运行ning,如果是,则转到第二个 script.sh 的执行,如果不,等到完成。

有什么帮助吗?

您可以将exec方法返回的Process实例存储在一个变量中,然后调用Process#isAlive查看它是否仍然是运行。

示例:

Process p = Runtime.getRuntime().exec("script.sh");
Thread.currentThread().wait(100);
if(p.isAlive()){
     // Do something
}

记录流程实例后:

 Process p = Runtime.getRuntime().exec(cmd);

你可以调用它来等待它在你希望的任何时间段之后结束:

 p.waitFor();

 p.waitFor(long timeout, TimeUnit unit)