系统相关
首页 > 系统相关> > 退出后,Java流程构建器子进程继续

退出后,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似乎停止了重启?它确实停止了,但不会重新开始.

解决方法:

您应该在退出之前等待您的流程完成:

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这样的库作为最后一部分.

标签:processbuilder,java,daemon
来源: https://codeday.me/bug/20190901/1782820.html