天天看點

Java Process 簡略使用方法以及坑點

Process可以用來開一個子程序,調用其他程式。

假設調用app.exe  工作目錄./dir 指令行參數 -arg1=1 -arg2=2 環境變量envp1=e1 envp2=e2

調用方法為

import java.io.*;

public class YccRuntime {

    public static void main(String[] arg) throws Exception {
        Runtime r = Runtime.getRuntime();
        //參數1 指令 參數2 環境變量(沒有就設定為null) 參數3 工作目錄
        Process p = r.exec("app.exe -arg1=1 -arg2=2", new String[]{"envp1=e1","envp2=e2"}, new File(".\\dir\\"));

        //擷取程序的輸入輸出流,由于windows預設編碼為gbk,是以需要特别設定一下編碼,不然輸出中文會出現亂碼
        //out輸出流,向子程序寫入資料
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream(), "GBK"));
        //in輸入流,擷取子程序的輸出
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream(), "GBK"));
        //err輸入流,擷取子程序列印的錯誤資訊
        BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream(), "GBK"));

        //一方面輸入輸出流的緩沖區有限,要及時處理,否則會阻塞
        //另外一方面,如果輸入流中沒有資料,調用readLine()方法會造成阻塞,
        //是以建議單獨開一個線程處理輸入流,但這裡作為示範,就不這麼做了

        //擷取子程序三行輸出
        System.out.println(in.readLine());
        System.out.println(in.readLine());
        System.out.println(in.readLine());

        //向子程序寫入資料 122 234 注意結尾加個換行符,否則子程序會以為你輸入還沒結束
        out.write("122 234\n");
        //務必調用flush方法把資料寫入
        out.flush();
        //擷取子程序一行輸出
        System.out.println(in.readLine());

        //輸入資料讓子程序結束
        out.write("end\n");
        out.flush();
        //程序結束,輸入流沒有更多資料,此時調用readLine會遇到EOF終止符,傳回null
        System.out.println(in.readLine());
        //如果有錯誤資訊,會輸出資訊但是本程式沒有,是以和in一樣,輸出null
        System.out.println("錯誤資訊:"+err.readLine());
        //等待子程序結束
        p.waitFor();

        System.out.println("程序結束 傳回值"+p.exitValue());
    }
}
           

app.exe的代碼如下

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstdio>
using namespace std;

int main(int argcnt,char **args)
{
    for(int i=1;i<argcnt;++i)
        printf("參數 %s ",args[i]);
    //每次輸出要記得輸出換行符,以及調用fflush(stdout)把輸出寫入到流中
    printf("\n");
    fflush(stdout);

    printf("envp1=%s\n",getenv("envp1"));
    printf("envp2=%s\n",getenv("envp2"));
    fflush(stdout);
    int x,y;
    while(1){
        if(scanf("%d",&x)!=1)
            break;
        if(scanf("%d",&y)!=1)
            break;
        printf("%d\n",x+y);
        fflush(stdout);
    }

    return 0;
}