之前一直使用Process执行shell命令,但是没有考虑过shell是正常结束(即exit 0)还是异常结束,最近一个项目需要获取shell执行的状态,Process刚好有一个api:exitValue(),调研下JDK文档:

可以看到exitValue为非阻塞的,如果Process没有执行完毕,调用会抛出异常,做个试验:

import java.io.IOException;

/**
 * Created by bo on 2019/9/6.
 */
public class Test {

    public static void main(String[] args) throws IOException, InterruptedException {
        Process pr = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","sh test.sh"});
        pr.exitValue();
        pr.waitFor();
    }

}

执行抛出异常如下:

调整下代码结构:

    public static void main(String[] args) throws IOException, InterruptedException {
        Process pr = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","sh test.sh"});
        pr.waitFor();
        System.out.println(pr.exitValue());
    }

再次运行,可以执行打印出系统结束状态为0,即正常结束:

在shell的末尾添加exit 1,即异常结束:

再次运行打印,系统结束状态返回值为1,即异常结束:

这里我调用了是waitFor()等待进程执行完毕,我在代码中是通过读取标准输出流来判断进程是否结束:

    public static void main(String[] args) throws IOException, InterruptedException {
        Process pr = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "sh test.sh"});
        BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String result;
        while ((result = br.readLine()) != null) {
            System.out.println(result);
        }
        br.close();
        System.out.println(pr.exitValue());
    }

注意:while结束后,必须执行close函数,关闭输出流,不然进程还是未结束状态,直接执行exitValue()还是会抛出异常。

更多推荐

Java Process exitValue()