2016-12-22 171 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進程。