SORU
30 NİSAN 2009, PERŞEMBE


Nasıl'Zamanı s.Java kullanarak bir zaman aşımı değeri eklemek için() exec?

Yerel ana bilgisayarda bir komut çalıştırmak için kullandığım bir yöntem var. Eğer komutu çağrıldığını makul bir süre içinde bitirmek değilse bile bu yöntem bir hata kodu ile geri döner bu yüzden bu yöntem için bir zaman aşımı parametre eklemek istiyorum. Sanki şimdiye kadar, zaman aşımı için yeteneği olmadan görünüyor:

public static int executeCommandLine(final String commandLine,
                                     final boolean printOutput,
                                     final boolean printError)
    throws IOException, InterruptedException
{
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(commandLine);

    if (printOutput)
    {
        BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        System.out.println("Output:  "   outputReader.readLine());
    }

    if (printError)
    {
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        System.out.println("Error:  "   errorReader.readLine());
    }

    return process.waitFor();
}

Kimse bana bir zaman aşımı parametresini uygulamak için iyi bir yol önerebilirsiniz?

CEVAP
30 NİSAN 2009, PERŞEMBE


public static int executeCommandLine(final String commandLine,
                                     final boolean printOutput,
                                     final boolean printError,
                                     final long timeout)
      throws IOException, InterruptedException, TimeoutException {
  Runtime runtime = Runtime.getRuntime();
  Process process = runtime.exec(commandLine);
  /* Set up process I/O. */
  ... 
  Worker worker = new Worker(process);
  worker.start();
  try {
    worker.join(timeout);
    if (worker.exit != null)
      return worker.exit;
    else
      throw new TimeoutException();
  } catch(InterruptedException ex) {
    worker.interrupt();
    Thread.currentThread().interrupt();
    throw ex;
  } finally {
    process.destroy();
  }
}

private static class Worker extends Thread {
  private final Process process;
  private Integer exit;
  private Worker(Process process) {
    this.process = process;
  }
  public void run() {
    try { 
      exit = process.waitFor();
    } catch (InterruptedException ignore) {
      return;
    }
  }  
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • engineerguy

    engineerguy

    10 Ocak 2010
  • KittiesMama

    KittiesMama

    10 AĞUSTOS 2008
  • Tomas N

    Tomas N

    14 Kasım 2010