【发布时间】:2012-07-31 02:46:09
【问题描述】:
这是我的示例代码,我想在运行新的子进程时处理来自标准输入的命令。但是,如果我读取 system.in,exec 方法将永远不会返回。 exec() 中的命令非常简单,与标准输入无关。
我想知道有没有办法解决这个问题?如何在启动另一个读取标准输入的线程时启动一个新的子进程?
public static void main(String[] args){
new Thread(new Runnable(){
public void run(){
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String command = null;
try{
while((command = reader.readLine()) != null){
System.out.println("Command Received:" + command);
}
}catch(Exception ex){
ex.printStackTrace();
//failed to listening command
}
}
}).start();
Process process = null;
try {
process = Runtime.getRuntime().exec("java -cp C:/agenttest Test");
System.out.println("never returns");
process.waitFor();
} catch (IOException e) {
throw new RuntimeException( e );
} catch (InterruptedException e) {
throw new RuntimeException( e );
}
}
Test类很简单,这里是Test.java
public static void main(String[] args){
System.out.println("Standard out");
System.out.println("Standard out");
System.err.println("Standard err");
System.out.println("Standard out");
try{
Thread.sleep(10000);
}catch(InterruptedException ex){}
}
【问题讨论】:
-
java -cp C:/agenttest Test到底应该做什么,这与您从 System.in 读取有什么关系? -
1) 使用
ProcessBuilder来构建Process,这样会更容易...... 2) 实施链接自runtime.execinfo. page 的文章的所有建议。 3) 显示的代码出现了不消耗错误流的经典错误,以及其他各种错误。 -
其实和system.in无关。该程序只是将一些输出打印到标准输出。我认为将其更改为任何其他程序都不会对结果进行任何更改。 @JonLin
-
是的,我已经打包了 runtime.exec,感谢 ProcessBuilder 的建议。我只是想说明这些奇怪的事情。 @安德鲁汤普森
-
您的代码对我有用,我怀疑问题出在您对 Test 类的调用中。
标签: java multiprocessing stdin runtime.exec