2012-04-04 88 views
0

這是我的代碼,通過Java在Windows中啓動一個進程(併吞噬輸出)。runtime.exec立即發送EOF輸入?

public static void main(String[] args) throws Exception { 
    String[] command = new String[3]; 
    command[0] = "cmd"; 
    command[1] = "/C"; 
    command[2] = "test.exe"; 
    final Process child = Runtime.getRuntime().exec(command); 
    new StreamGobbler(child.getInputStream(), "out").start(); 
    new StreamGobbler(child.getErrorStream(), "err").start(); 
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
      child.getOutputStream())); 
    out.write("exit\r\n"); 
    out.flush(); 
    child.waitFor(); 
} 

private static class StreamGobbler extends Thread { 
    private final InputStream inputStream; 
    private final String name; 

    public StreamGobbler(InputStream inputStream, String name) { 
     this.inputStream = inputStream; 
     this.name = name; 
    } 

    public void run() { 
     try { 
      BufferedReader in = new BufferedReader(new InputStreamReader(
        inputStream)); 
      for (String s = in.readLine(); s != null; s = in.readLine()) { 
       System.out.println(name + ": " + s); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

不知何故在問題(處理)程序(在右作爲後餘步驟PAS的「EXEC」線)recieving一個EOF馬上並且因此運行時間之後立即發出一個錯誤(檢測到的,無效的)消息。 exec被調用。我可以通過命令提示符手動運行此程序,而不會出現此問題,但已經確認在Windows上發送ctrl-z是導致此消息的原因。

任何人都知道這可能是導致此?

如果很重要,我已經嘗試直接運行該過程作爲「test.exe」而不是cmd/c test.exe,但是當我這樣做時,我看不到輸出通過inputStream。而當我沒有/ c做cmd test.exe時,沒有任何區別。

回答

1

你的代碼看起來應該起作用(有一個警告,見下文)。

我把你的代碼逐字記錄下來,用sort代替test.ext,它可以從管道標準輸入讀取。

如果我按原樣運行代碼,它將啓動sort命令,該命令將等待輸入。它掛在child.waitFor(),因爲您不關閉輸出流來指示EOF。當我添加close()調用時,一切正常。

我建議你看看test.exe並確定它是否能夠從管道標準輸入讀取,或正在期望控制檯輸入。

+0

謝謝吉姆,那正是我需要的。它確實看起來像程序沒有像sort或其他cmd行實用程序那樣處理stdin。 – user1309154 2012-04-04 13:26:06

0

擺脫「cmd」和「/ c」。目前你正在輸出到cmd.exe,而不是test.exe。

+0

問題是,當我做你說的話,我不知道如何通過InputStream從程序接收任何標準輸出,就像我現在所做的那樣,正如我在帖子末尾提到的那樣。你知道爲什麼會這樣嗎?我正在使用cmd/c,因爲它可以與除此特定命令行之外的其他任何命令行工具一起使用。 – user1309154 2012-04-04 03:06:18

+0

@ user1309154請參閱Jim Garrison的回答。在調用'waitFor()'之前,你一定要關閉輸出流。 – EJP 2012-04-04 09:18:44