Process.getInputStream()阻塞问题
Java中
Runtime.getInstance().exec (String cmd)
|
或者
new ProcessBuilder(String cmd).start()
|
都可以产生子进程对象Process。通过调用Process对象的waitFor()方法可以使主进程进入等待状态,直至子进程执行完毕,再进行下一步工作。如果对子进程处理不当,有可能造成主进程阻塞,整个程序死掉。
java Api中关于Process说的是:
ProcessBuilder.start() 和 Runtime.exec 方法创建一个本机进程,并返回 Process 子类的一个实例,该实例可用来控制进程并获取相关信息。Process 类提供了执行从进程输入、执行输出到进程、等待进程完成、检查进程的退出状态以及销毁(杀掉)进程的方法。
创建进程的方法可能无法针对某些本机平台上的特定进程很好地工作,比如,本机窗口进程,守护进程,Microsoft Windows 上的 Win16/DOS 进程,或者 shell 脚本。创建的子进程没有自己的终端或控制台。它的所有标准 io(即 stdin,stdout,stderr)操作都将通过三个流 (getOutputStream(),getInputStream(),getErrorStream()) 重定向到父进程。父进程使用这些流来提供到子进程的输入和获得从子进程的输出。因为有些本机平台仅针对标准输入和输出流提供有限的缓冲区大小,如果读写子进程的输出流或输入流迅速出现失败,则可能导致子进程阻塞,甚至产生死锁。
在对getOutputStream(),getInputStream(),getErrorStream()的描述中,有个注意事项:对其输出流和错误流进行缓冲是一个好主意!嗯,好抽象啊!
问题正在于此,Process.getInputStream()和Process.getErrorStream()分别返回Process的标准输出流和错误流,两个流如果处理不当,其缓冲区不能被及时清除而被塞满,则进程被阻塞,即使调用Process.destory()也未必能销毁被阻塞的子进程。
如果尝试同步获取Process的输出流和错误流进行处理,未必有效,顺序执行过程中,输出流和错误流常常不能得到及时处理。解决方案有两个。
方案一:并发获取Process的输出流和错误流
通过启动两个线程来并发地读取和处理输出流和错误流,懒得打开IDE了,就大概敲一下代码吧,可能有错误,如下:
调用者:
class ProcessExecutor
{
private Process p;
private List<String> outputList;
private List<String> errorOutputList;
public ProcessExecutor(Process p) throws IOException
{
if(null == p)
{
throw new IOException("the provided Process is null");
}
this. p = p;
}
public List<String> getOutputList()
{
return this. outputList;
}
public List<String> getErrorOutputList()
{
return this.errorOutputList;
}
public int execute()
{
int rs = 0;
Thread outputThread = new ProcessOutputThread(this.p.getInputStream());
Thread errorOutputThread = new ProcessOutputThread(this.p.getErrorStream());
outputThread.start();
errorOutputThread.start();
rs = p.waitFor();
outputThread.join();
errorOutputThread.join();
this.outputList = outputThread.getOutputList();
this.errorOutputList = errorOutputThread.getOutputList();
return rs;
}
}
|
流处理线程
class ProcessOutputThread extends Thread
{
private InputStream is;
private List<String> outputList;
public ProcessOutputThread(InputStream is) throws IOException
{
if(null == is)
{
throw new IOException("the provided InputStream is null");
}
this. is = is;
this.outputList = new ArrayList<String>();
}
public List<String> getOutputList()
{
return this. outputList;
}
@Override
public void run()
{
InputStreamReader ir = null;
BufferedReader br = null;
try
{
ir = new InputStreamReader(this.is);
br = new BufferedReader(ir);
String output = null;
while(null != (output = br.readLine()))
{
print(output);
this.outputList.add(output);
}
}
catch(IOException e)
{
e.print();
}
finally
(
try
{
if(null != br)
{
br.close();
}
if(null != ir)
{
ir.close();
}
if(null != this.is)
{
this.is.close();
}
}
catch(IOException e)
{
e.print();
}
)
}
}
|
方案二:用ProcessBuilder的redirectErrorStream()方法合并输出流和错误
public int execute()
{
int rs = 0;
String[] cmds = {...};//command and arg
ProcessBuilder builder = new ProcessBuilder(cmds);
builder.redirectErrorStream(true);
Process process = builder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output = null;
while (null != (readLine = br.readLine()))
{
print(output);
}
rs = process.waitFor();
return rs;
}
|
Java Process 阻塞测试总结
Process阻塞原因:输入流和错误流分开的,没有处理,就会发生阻塞,归根结底本质上是bio引起的io阻塞问题。
getInputStream,getErrorSteam就是获取脚本或者命令的控制台回显信息,前者获取的是标准输出的回显信息,后者获取的是标准错误的回显信息
Process原理:使用Runtime.getRuntime().exec(cmd)会在当前进程建立一个子进程,子进程由于没有控制台,它的标准输出和标准错误就会返回给父进程Process,因此通过getInputStream和getErrorStream就可以获取到这些信息。
测试代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JavaExeBat {
public JavaExeBat() {
}
public static void main(String[] args) {
Process p;
//test.bat中的命令是ipconfig/all
String cmd="sh test.sh ";
//String cmd="ping 127.0.0.1 -c 4";
try {
//执行命令
p = Runtime.getRuntime().exec(cmd);
//取得命令结果的输出流
//输出流
InputStream fis=p.getInputStream();
//错误流
InputStream ferrs=p.getErrorStream();
//用一个读输出流类去读
InputStreamReader isr=new InputStreamReader(fis);
InputStreamReader errsr=new InputStreamReader(ferrs);
//用缓冲器读行
BufferedReader br=new BufferedReader(isr);
BufferedReader errbr=new BufferedReader(errsr);
String line=null;
String lineerr = null;
//直到读完为止
while((line=br.readLine())!=null) {
//有可能发生阻塞的问题
System.out.println("return input Str:" + line);
}
while((lineerr=errbr.readLine())!=null){
//有可能发生阻塞的问题
System.out.println("return err Str:" + lineerr);
}
int exitVal = p.waitFor();
System.out.println("exitVal:" + exitVal);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
test.sh如下
#!/bin/bash
for((i=0; i < 100000; i++));do
//输出的标准输出
echo "testaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
//输出到标准错误
echo "testaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 1>&2
done
|
经过测试发现,如果JavaExeBat.java文件中只开启标准输出或者标准错误时,进程就会夯住,无法通过waiteFor获取其返回值,因为脚本中分别输出了100000w条信息到标准输出和标准错误,而下述代码只处理了getInputStream,导致标准错误输出流的信息太多返回给当前进程,没有得到处理,因此阻塞。
代码如下:
p = Runtime.getRuntime().exec(cmd);
//取得命令结果的输出流
//输出流
InputStream fis=p.getInputStream();
//用一个读输出流类去读
InputStreamReader isr=new InputStreamReader(fis);
//用缓冲器读行
BufferedReader br=new BufferedReader(isr);
String line=null;
//直到读完为止
while((line=br.readLine())!=null) {
//有可能发生阻塞的问题
System.out.println("return input Str:" + line);
}
int exitVal = p.waitFor();
System.out.println("exitVal:" + exitVal);
|
把上述代码中的getInputStream换做getErrorStream,也会夯住进程,因为同样只处理了两者中一者,即标准错误。
那么能不能同步处理两个流信息呢?代码如下:
try {
//执行命令
p = Runtime.getRuntime().exec(cmd);
//取得命令结果的输出流
//输出流
InputStream fis=p.getInputStream();
//错误流
InputStream ferrs=p.getErrorStream();
//用一个读输出流类去读
InputStreamReader isr=new InputStreamReader(fis);
InputStreamReader errsr=new InputStreamReader(ferrs);
//用缓冲器读行
BufferedReader br=new BufferedReader(isr);
BufferedReader errbr=new BufferedReader(errsr);
String line=null;
String lineerr = null;
//直到读完为止
while((line=br.readLine())!=null) {
//有可能发生阻塞的问题
System.out.println("return input Str:" + line);
}
while((lineerr=errbr.readLine())!=null){
//有可能发生阻塞的问题
System.out.println("return err Str:" + lineerr);
}
int exitVal = p.waitFor();
System.out.println("exitVal:" + exitVal);
} catch (Exception e) {
e.printStackTrace();
}
}
|
测试过后发现也不行,因为是同步的,就会有先后顺序,也会发生阻塞,测试方法,将test.sh改为只打印标准错误,就会发现标准错误处理被阻塞,脚本如下:
#!/bin/bash
for((i=0; i < 100000; i++));do
//输出到标准错误
echo "testaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 1>&2
done
|
解决办法思路:
(1)并发处理两个流信息,开启两个线程分别处理输出流与错误流
(2)将两个流合并为一个流解决示例:
第一种思路:
class ProcessExecutor
{
private Process p;
private List<String> outputList;
private List<String> errorOutputList;
public ProcessExecutor(Process p) throws IOException
{
if(null == p)
{
throw new IOException("the provided Process is null");
}
this. p = p;
}
public List<String> getOutputList()
{
return this. outputList;
}
public List<String> getErrorOutputList()
{
return this.errorOutputList;
}
public int execute()
{
int rs = 0;
Thread outputThread = new ProcessOutputThread(this.p.getInputStream());
Thread errorOutputThread = new ProcessOutputThread(this.p.getErrorStream());
outputThread.start();
errorOutputThread.start();
rs = p.waitFor();
outputThread.join();
errorOutputThread.join();
this.outputList = outputThread.getOutputList();
this.errorOutputList = errorOutputThread.getOutputList();
return rs;
}
}
class ProcessOutputThread extends Thread
{
private InputStream is;
private List<String> outputList;
public ProcessOutputThread(InputStream is) throws IOException
{
if(null == is)
{
throw new IOException("the provided InputStream is null");
}
this. is = is;
this.outputList = new ArrayList<String>();
}
public List<String> getOutputList()
{
return this. outputList;
}
@Override
public void run()
{
InputStreamReader ir = null;
BufferedReader br = null;
try
{
ir = new InputStreamReader(this.is);
br = new BufferedReader(ir);
String output = null;
while(null != (output = br.readLine()))
{
print(output);
this.outputList.add(output);
}
}
catch(IOException e)
{
e.print();
}
finally
(
try
{
if(null != br)
{
br.close();
}
if(null != ir)
{
ir.close();
}
if(null != this.is)
{
this.is.close();
}
}
catch(IOException e)
{
e.print();
}
)
}
}
|
第二种思路:使用ProcessBuilder,将其redirectErrorStream(true);将输出流与错误流合并
public int execute()
{
int rs = 0;
String[] cmds = {...};//command and arg
ProcessBuilder builder = new ProcessBuilder(cmds);
builder.redirectErrorStream(true);
Process process = builder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String output = null;
while (null != (readLine = br.readLine()))
{
print(output);
}
rs = process.waitFor();
return rs;
}
|