【问题标题】:launch multiple instances of an executable and manage them启动可执行文件的多个实例并管理它们
【发布时间】:2012-07-23 18:15:55
【问题描述】:

我有很多个进程正在运行

Runtime rt = Runtime.getRuntime();
int i=0;
int arg1;
while(i<10){
    arg1 = i+1;
    Process p = rt.exec("abc.exe "+ arg1);
    i++;
}

每个进程都使用不同的参数值运行这里 arg1 是该进程 abc.exe 的参数,我想检查所有这些进程是否正在运行或其中任何一个崩溃。如果发生崩溃,我想重新启动它。如何跟踪所有这些过程并定期检查它们是否崩溃?

我可以在 Linux 和 Windows 上跟踪这个东西吗?阅读一些关于它的文章,但这一篇有点不同,因为它涉及多次出现,并且只需要检查一些特定的过程......

【问题讨论】:

    标签: java multithreading exec pid


    【解决方案1】:

    Runtime.exec(...) 命令返回一个Process 对象。您可以将Process 对象放入一个集合中,然后使用Process.exitValue() 方法查看每个进程是否已完成。如果进程仍在运行,exitValue() 会抛出 IllegalThreadStateException

    所以你的代码可能是这样的:

    List<Process> processes = new ArrayList<Process>();
    // noticed I turned your while loop into a for loop
    for (i = 0; i < 10 i++) {
        int arg1 = i + 1;
        Process p = rt.exec("abc.exe "+ arg1);
        processes.add(p);
    }
    ...
    // watch them to see if any of them has finished
    // this can be done periodically in a thread
    for (Process process : processes) {
       try {
           if (process.exitValue() != 0) {
               // it did not exit with a 0 so restart it
               ...
           }
       } catch (IllegalThreadStateException e) {
           // still running so we can ignore the exception
       }
    }
    

    我可以在 Linux 和 Windows 上跟踪这个东西吗?

    如果我理解这个问题,上面的代码应该可以在 Lunux 和 Windows 上运行。

    【讨论】:

      【解决方案2】:

      使用进程构建器,然后保留进程 ID,您可以使用它来管理您启动的任何进程。 Runtime.exec(...) 应该保留给您需要执行的“一次性”命令。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多