简体   繁体   English

退出后,Java流程构建器子进程继续

[英]Java processbuilder child processes continue after exit

I'm working on an auto-update script that should be able to restart the daemon once it completes. 我正在开发一个自动更新脚本,该脚本应该能够在守护程序完成后重新启动它。

I'm currently trying this: 我正在尝试这个:

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

However the System.exit seems to stop the restart? 但是System.exit似乎停止了重启? It does actually stop, but does not start again. 它确实停止了,但不会重新开始。

You should definitely wait for your process to complete before exiting: 您应该在退出之前等待您的流程完成:

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

And you should consume the output stream of the process, as it can cause the process to block if the output buffer becomes full. 并且您应该使用进程的输出流,因为如果输出缓冲区变满,它可能导致进程阻塞。 Not sure if this is applicable to your scenario but its a best practice in any case: 不确定这是否适用于您的方案,但在任何情况下都是最佳做法:

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

You can also use a library like Apache IOUtils for the last part. 您还可以使用像Apache IOUtils这样的库作为最后一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM