0

現在、スクリプトを介して開始するJavaクラスがあります

Process proc = Runtime.getRuntime().exec(" run my script");

特定の理由により、これはほぼ常に実行されます。スクリプトがなんらかの理由で停止した場合、Java クラスはスクリプトを再開します。

今、私はときどきプロセスを時々強制終了する必要があります。そこで、特定の時間待機してからプロセスを強制終了するスレッドを開始することにしました。Java のメイン クラスなどは、プロセスが終了したことを確認してから、プロセスを再開します。

このスレッドにプロセスを表示させ、その後頻繁に強制終了させる方法がわかりません。そのスレッドを作成する方法について何か提案はありますか? 注意として、私はしばらくスレッドを扱う必要がなかったので、少し錆びています。

私がやっていることの基本的な考え方を理解するための私のクラスの単純な疑似コード:

Class MyClass{

    Process mProc;

    main(args){
        do{
            try{
                mProc = Runtime.getRuntime().exec("cmd /C myScript");
                mProc.destroy();
            } catch(Exception e){
                Log(e);
            }
        } while(true);
4

1 に答える 1

1

このスレッドにプロセスを表示させ、その後頻繁に強制終了させる方法がわかりません。

Java 6 の時点では、これを行うのは現在簡単ではありません。Processクラスにはメソッドがありますが、内部的に呼び出すだけでwaitFor()あることを考えると、悲劇的なタイムアウトはかかりません。wait()UnixProcess

できることは、ハックのようなものですが、 で同期して自分自身Processを呼び出すことwait(timeoutMillis)です。何かのようなもの:

Process proc = new ProcessBuilder().command(commandArgs).start();
long startMillis = System.currentTimeMillis();
synchronized (proc) {
    proc.wait(someTimeoutMillis);
}
long diff = System.currentTimeMillis() - startMillis;
// if we get here without being interrupted and the delay time is more than
// someTimeoutMillis, then the process should still be running
if (diff >= someTimeoutMillis) {
   proc.destroy();
}

問題は、競合状態があり、同期するprocにプロセスが終了した場合、永遠に待機することです。別の解決策は、1 つのスレッドで実行proc.waitFor()し、タイムアウトになったら別のスレッドで中断することです。

Process proc = new ProcessBuilder().command(commandArgs).start();
try {
   // this will be interrupted by another thread
   int errorCode = proc.waitFor();
} catch (InterruptedException e) {
   // always a good pattern to re-interrupt the thread
   Thread.currentThread().interrupt();
   // our timeout must have expired so we need to kill the process
   proc.destroy();
}
// maybe stop the timeout thread here

別のオプションはproc.exitValue()、プロセスが実行されたかどうかをテストできる を使用することです。残念ながら、終了していない場合に返す-1か、これがスローする代わりに。IllegalThreadStateException

于 2013-05-09T14:54:24.250 に答える