简体   繁体   中英

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? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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