j*******s 发帖数: 81 | 1 想实现“ls -l | sort”
开两个进程,一个运行ls -l,另一个运行sort,进程1的输出作为进程2的输入,可是
似乎
进程2没收到,谁能帮我看看下面代码的问题?
public void runStep0(){
try {
Process proc1 = Runtime.getRuntime().exec("ls -l");
InputStream stdin1 = proc1.getInputStream(); //
InputStreamReader isr1 = new InputStreamReader(stdin1);
BufferedReader br1 = new BufferedReader(isr1);
Process proc2 = Runtime.getRuntime().exec("sort");
InputStream stdin2 = proc1.getInputStream();
| Z****e 发帖数: 2999 | 2 when piping two processes, the data flows like this:
-> stdin1 -> proc1 -> stdout1 -> pipe -> stdin2 -> proc2 -> stdout2
when any of the stdin/outs blocks, the whole system will block
and I think this is what happened with your code, you are reading from
stdout1 first, dump it to stdin2, then read data from stdout2, but these two
should be done concurrently
so you need a separate thread to act as the pipe, e.g.
class StreamPipe extends Thread{
private InputStream is;
private OutputStream o
【在 j*******s 的大作中提到】 : 想实现“ls -l | sort” : 开两个进程,一个运行ls -l,另一个运行sort,进程1的输出作为进程2的输入,可是 : 似乎 : 进程2没收到,谁能帮我看看下面代码的问题? : public void runStep0(){ : try { : Process proc1 = Runtime.getRuntime().exec("ls -l"); : InputStream stdin1 = proc1.getInputStream(); // : InputStreamReader isr1 = new InputStreamReader(stdin1); : BufferedReader br1 = new BufferedReader(isr1);
|
|