Today using NIO to write a similar SSH network client, in the execution of the process, there is a very annoying bug, nonsense, the code:
Public Static voidMain (string[] args)throwsException {Process process=runtime.getruntime (). EXEC ("cmd/c tree"); intstatus=Process.exitvalue (); SYSTEM.OUT.PRINTLN (status); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (Process.getinputstream ())); String Line=NULL; while((Line=reader.readline ())! =NULL) {System.out.println (line); } BufferedReader Error=NewBufferedReader (NewInputStreamReader (Process.geterrorstream ())); while((Line=error.readline ())! =NULL) {System.out.println (line); } }
Immediately after the process is called
int status=process.exitvalue ();
Came up
Java.lang.IllegalThreadStateException:process have not exited
At Java.lang.Win32Process.exitValue (Native Method)
Exception, background 100 degree discovery, the JDK implementation process, call External command is not synchronous call, but asynchronous execution. So the tree command returns without executing successfully, and the JDK throws an exception.
Later I thought of a trick, that is, regardless of how to do, first read the process of InputStream and Errorinputstream, that is to say
Whether the external command executes correctly or not, it is executed first.
//read the correct execution of the return streamBufferedReader info=NewBufferedReader (NewInputStreamReader (Executor.getinputstream ())); while((Line=info.readline ())! =NULL) {infomsg.append (line). Append ("\ n"); }//read error execution of return streamBufferedReader error=NewBufferedReader (NewInputStreamReader (Executor.geterrorstream ())); while((Line=error.readline ())! =NULL) {errormsg.append (line). Append ("\ n"); }//call Exitvalue return valueResponsecode=executor.exitvalue ();
At this point, the call to Exitvalue () method will not go wrong.
This is a concrete example of
intResponsecode=0; StringBuilder infomsg=NewStringBuilder (); StringBuilder errormsg=NewStringBuilder (); 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=NewBufferedReader (NewInputStreamReader (Executor.getinputstream ())); BufferedReader Error=NewBufferedReader (NewInputStreamReader (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 ();
http://kingj.iteye.com/blog/1420586
Traps for Java process on Windows (GO)