2016-12-22 89 views
2

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

以下是样本代码。

/// 
/// 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); 
} 

回答

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进程。