2017-01-09 30 views
0

我試圖從批處理腳本運行AWS-CLI以與S3同步文件,然後自動關閉cmd窗口。從批處理腳本中使用AWS CLI似乎阻止Process.waitFor完成

在沒有涉及AWS-CLI的所有批處理腳本中,Process.waitFor方法都會導致cmd窗口在進程執行完成時自動退出,但當我有AWS CLI命令時,情況並非如此。

S3 Sync將完成,我將留下一個打開的cmd窗口,程序將不會繼續,直到我手動關閉它。

爲了使Process.waitFor在這種情況下工作,或者在腳本完成時自動關閉cmd窗口,是否有特殊的事情需要我做?

此問題是獨一無二的,因爲該命令通常返回正常,但不在使用AWS CLI的特定情況下。

+0

的可能的複製[process.waitFor()永遠不會返回(http://stackoverflow.com/questions/5483830/process-waitfor-never-returns) – teppic

回答

1

你可能不讀取進程輸出,所以它試圖寫入標準輸出時被阻塞。

這個工作對我來說:

import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.concurrent.CompletableFuture; 

public class S3SyncProcess { 

    public static void main(String[] args) throws IOException, InterruptedException { 
     // sync dir 
     Process process = Runtime.getRuntime().exec(
      new String[] {"aws", "s3", "sync", "dir", "s3://my.bucket"} 
     ); 

     CompletableFuture.runAsync(() -> pipe(process.getInputStream(), System.out)); 
     CompletableFuture.runAsync(() -> pipe(process.getErrorStream(), System.err)); 

     // Wait for exit 
     System.exit(process.waitFor()); 
    } 

    private static void pipe(InputStream in, OutputStream out) { 
     int c; 
     try { 
      while ((c = in.read()) != -1) { 
       out.write(c); 
      } 
     } catch (IOException e) { 
      // ignore 
     } 
    } 

}