Java calls Bash shell script blocking small problem resolution
Background
Using Java implementation of the Web side, the web side of the corresponding user interface operation, using Java Call Bash implementation of the shell script to do the actual operation, the operation is completed to return the results of execution to the Web interface display.
Phenomenon:
The Java process is blocked. Use the PS command to see the execution process status of the invoked shell as s
Analysis
The state of the Shell subprocess is the S sleep state, which means that the process waits for a condition to be satisfied before it can continue execution.
After the Java program calls Runtime.getruntime (). EXEC (Jyname), Linux creates a process to execute the program, which uses three pipelines between the JVM to link standard input, standard output, and standard error.
Assuming that the sub-process has been writing to standard output or standard error and the JVM is not read uniformly, if the corresponding standard error standard output buffer is written full, then the child process will wait until the buffer has space to continue execution. The child process enters sleep mode. Our Java program is also blocked in the process.waitfor ();
Solutions
- Do not have too much output in the calling program to standard error, standard output.
- The JVM and our Java program read the standard output and standard error of the subprocess to avoid full buffers.
Realize:
Programme I
Import Java.io.InputStreamReader;
Import Java.io.LineNumberReader;
Import java.util.ArrayList;
Import java.util.List;
/*
* Javac Helloworld.java
* Java HelloWorld
*
*/
public class HelloWorld {
/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
System.out.printf ("Just test!\n");
String cmd1= "/data/dt/bin/get.py";
String cmd2= "/data/d/bin/packms.sh";
List ret;
try {
Ret=runshell (CMD1);
Ret=runshell (CMD2);
System.out.printf ("Just Test:" +ret.tostring ());
Runshell (CMD2);
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
/**
* Run shell
*
* @param shstr
* The shell need to run
* @return
* @throws IOException
*/
public static List Runshell (String shstr) throws Exception {
list<string> strlist = new ArrayList ();
Process process;
Process = Runtime.getruntime (). EXEC (new string[]{"/bin/sh", "-ci", shstr},null,null);
InputStreamReader ir = new InputStreamReader (process
. getInputStream ());
LineNumberReader input = new LineNumberReader (IR);
String Line;
Process.waitfor ();
while (line = Input.readline ()) = null) {
Strlist.add (line);
}
return strlist;
}
}
Programme II
Make up later
Reference links
http://www.ituring.com.cn/article/details/130
http://siye1982.iteye.com/blog/592405
Http://www.linuxidc.com/Linux/2014-04/99557.htm
Http://www.51testing.com/html/48/202848-236743.html
Java calls Bash shell script blocking small problem resolution