【问题标题】:Java : Running shell script in backgroundJava:在后台运行 shell 脚本
【发布时间】:2016-12-22 14:24:12
【问题描述】:

我试图在后台运行一个在我的函数/进程结束时不会终止的 shell 脚本。然而,似乎尽管 nohup,当 java 线程结束时。脚本也是如此。

下面是示例代码。

///
/// Tries to run a script in the background
///
try {
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("nohup sh ./runner.sh > output.txt &", new String[] {}, wrkDir);
    // pr.waitFor(); // Intentionally not using
} catch(Exception e) {
    throw new RuntimeException(e);
}

【问题讨论】:

    标签: java multithreading shell


    【解决方案1】:

    nohup 适用于来自 shell 的调用,而不是来自调用程序的调用。

    可能有很多方法可以解决这个问题,但想到的一种方法是尝试修改您的 Java 代码以调用启动器 shell 脚本,该脚本调用 nohup runner.sh... 代码(无需启动 sh)。

    类似这样的(未经测试的)代码:

    Java 修订版:

    ///
    /// Tries to run a script in the background
    ///
    try {
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("sh ./launcher.sh", new String[] {}, wrkDir);
        // pr.waitFor(); // Intentionally not using
    } catch(Exception e) {
        throw new RuntimeException(e);
    }
    

    launcher.sh

    #!/bin/sh
    
    nohup ./runner.sh > output.txt &
    

    我不确定这里的重定向,但如果这可行(正如我所提到的,此解决方案未经测试),缺点是您会因尝试调用 runner 而失去反馈——该脚本中的任何错误您的 Java 进程将无法调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 2014-04-09
      • 2021-10-26
      • 1970-01-01
      相关资源
      最近更新 更多