【问题标题】:Can I get a Java app to wait for background processes to complete?我可以让 Java 应用程序等待后台进程完成吗?
【发布时间】:2015-05-16 15:59:04
【问题描述】:

我有一个位于服务器上的 bash 脚本和一个将在所述服务器上运行的 Java 应用程序。我的目标是从 Java 应用程序中调用此脚本两次,以便两者同时运行。

我有以下代码:

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(new String[] { "/bin/bash", "-c", "script.sh & script.sh & " });

这应该通过 bash 调用脚本,在后台运行它,然后在第一次完成之前立即启动另一个脚本(脚本大约需要十秒钟才能运行)。这一切似乎都很好。

问题是,我想等到两个后台进程都完成后再继续我的 Java 程序的下一行。我试过这个:

int exitValue = process.waitFor();
// "next line of code"

但是,“下一行代码”似乎在两个进程真正完成之前就已经运行了。我怀疑正在发生的事情是,一旦第二个进程启动,Java 就会认为“进程”已完成,因为它们都在后台运行。我的猜测是 process.waitFor() 真的只适用于跟踪前台进程。

我想一种解决方案是制作一个临时 bash 脚本,在后台启动两个进程,在前台运行 那个 脚本,并使用 process.waitFor() 跟踪其进度。但我真的更希望不必继续创建调用其他脚本的临时脚本,以便它可以在前台运行。理想情况下,我想像今天这样调用后台进程,然后等待它们全部完成。我不知道这是否可能。

【问题讨论】:

  • 对于初学者,不要使用Runtime.exec(),而是使用ProcessBuilder。但是,是的,这是可能的。
  • 另外,如果一个脚本无法正确完成,或者两者都无法正确完成,会发生什么?

标签: java bash process background-process foreground


【解决方案1】:

您可以让其中的每一个都在子线程中运行,然后“加入”这些线程。

Runnable run1 = new Runnable()
{
    public void run()
    {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(new String[] { "/bin/bash", "-c", "script.sh & script.sh & " });
    }
}

Runnable run2 = new Runnable()
{
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(new String[] { "/bin/bash", "-c", "script2.sh & script2.sh & " });

}

Thread thread1 = new Thread(run1);
Thread thread2 = new Thread(run2);

thread1.start();
thread2.start();

thread1.join();
thread2.join();

【讨论】:

    【解决方案2】:

    我认为您可能不会在您的情况下创建后台 bash 命令。 & 用于在后台运行的命令,这将使真正的工作在后台运行,但告诉您 shell 已完成。

    Runtime runtime =  Runtime.getRuntime(); 
    Process process = runtime.exec(new String[] { "/bin/bash", "-c", "script.sh & script.sh " });
    

    【讨论】:

      猜你喜欢
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多