avatar
Process的问题# Java - 爪哇娇娃
j*s
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();
avatar
Z*e
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);

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。