天天看点

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;
}