2013-01-05 39 views
2

我正在開發一個自動更新腳本,該腳本應該能夠在完成後重新啓動守護進程。退出後Java進程構建器子進程繼續

目前,我正在嘗試此:

final ArrayList<String> command = new ArrayList<String>(); 
    String initScriptPath = Config.GetStringWithDefault("init_script", "/etc/init.d/my-daemon"); 
    command.add("/bin/bash"); 
    command.add("-c"); 
    command.add("'" + initScriptPath + " restart'"); 

    StringBuilder sb = new StringBuilder(); 
    for (String c : command) { 
     sb.append(c).append(" "); 
    } 
    Log.write(LogPriority.DEBUG, "Attempting restart with: " + sb.toString()); 

    final ProcessBuilder builder = new ProcessBuilder(command); 

    builder.start(); 

    // Wait for a couple of seconds 
    try { 
     Thread.sleep(5000); 
    } catch (Exception e) { 
    } 

    System.exit(0); 

然而System.exit似乎停止重啓?它確實停止,但不會重新開始。

+0

所以這裏的問題等於:「是否system.exit殺死子進程」? –

+0

@NathanHughes是的,我在標題中加入了更多的意義。 – RobinUS2

回答

5

你一定要等到你的進程退出之前完成:

final ProcessBuilder builder = new ProcessBuilder(command); 
builder.redirectErrorStream(true); 
final Process process = builder.start(); 
final int processStatus = process.waitFor(); 

你應該消耗過程的輸出流,因爲它可能會導致進程阻塞,如果輸出緩衝區已滿。不知道這是否適用於您的方案,但它在任何情況下,最好的做法:

String line = null; 
final BufferedReader reader = 
    new InputStreamReader (process.getInputStream()); 
while((line = reader.readLine()) != null) { 
    // Ignore line, or do something with it 
} 

你也可以使用一個圖書館一樣Apache IOUtils最後一部分。

+0

也確保您讀取進程的inputstream和errorstream,否則該進程可能會掛起。 – GreyBeardedGeek

+0

仍然無法使用。我目前擁有超過+ process.getInputStream()和process.getOutputStream()的所有內容。似乎沒有任何實際工作。你有什麼其他的建議? – RobinUS2

+0

定義不起作用?這個過程是否過早終止?它沒有完成?您是否在使用流程的輸出流? – Perception