今天使用nio编写一个类似ssh的网络客户端,在执行process的时候,出现了一个让人很头疼的bug,废话不说,上代码:
public static void main(String[] args)throws Exception {
Process process=Runtime.getRuntime().exec("cmd /c tree");
int status=process.exitValue();
System.out.println(status);
BufferedReader reader=new BufferedReader(new InputStreamReader(process.getInputStream()));
String line=null;
while((line=reader.readLine())!=null) {
System.out.println(line);
}
BufferedReader error=new BufferedReader(new InputStreamReader(process.getErrorStream()));
while((line=error.readLine())!=null) {
System.out.println(line);
}
}
在process后面立即调用后
int status=process.exitValue();
,出现了
java.lang.IllegalThreadStateException: process has not exited
at java.lang.Win32Process.exitValue(Native Method)
异常,后台一百度发现,jdk实现process时,调用外部命令不是同步的调用,而是异步执行。所以tree命令还没有执行成功就返回,jdk抛出异常。
后来想了一招,就是不管执行如何,先去读取process的InputStream和ErrorInputStream,也就是说
不管外部命令执行的正确与否,都先去执行一次。
//读取正确执行的返回流
BufferedReader info=new BufferedReader(new InputStreamReader(executor.getInputStream()));
while((line=info.readLine())!=null) {
infoMsg.append(line).append("\n");
}
//读取错误执行的返回流
BufferedReader error=new BufferedReader(new InputStreamReader(executor.getErrorStream()));
while((line=error.readLine())!=null) {
errorMsg.append(line).append("\n");
}
//调用exitValue返回值
responseCode=executor.exitValue();
这个时候,再调用exitValue()方法就不会出错了
这是一个具体的实例
int responseCode=0;
StringBuilder infoMsg=new StringBuilder();
StringBuilder errorMsg=new StringBuilder();
String line=null;
String cmd=Util.isWindows()?("cmd /c "+command):(command);
System.err.println("command is "+cmd);
Process executor=Runtime.getRuntime().exec(cmd);
BufferedReader info=new BufferedReader(new InputStreamReader(executor.getInputStream()));
BufferedReader error=new BufferedReader(new InputStreamReader(executor.getErrorStream()));
while((line=info.readLine())!=null) {
infoMsg.append(line).append("\n");
}
while((line=error.readLine())!=null) {
errorMsg.append(line).append("\n");
}
responseCode=executor.exitValue();