3

デーモンが完了すると再起動できる自動更新スクリプトに取り組んでいます。

私は現在これを試しています:

    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は再起動を停止しているようですか?実際には停止しますが、再開はしません。

4

1 に答える 1

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
}

最後の部分には、ApacheIOUtilsのようなライブラリを使用することもできます。

于 2013-01-05T19:50:07.907 に答える