我的应用程序使用单独线程中的进程来运行一些命令并从中获取输入:
process = Runtime.getRuntime().exec("su");
out = new DataOutputStream(process.getOutputStream());
该应用程序向进程发送命令,如下所示:
public void setCommands(String[] commands)
{
try{
for(String command : commands){
out.writeBytes(command + "\n");
}
out.writeBytes("exit\n"); //if I comment this line the commands get lost
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
然后线程使用 BufferedReaders 从进程读取输入并将其发送到主线程,它第一次工作正常。问题是我想通过多次调用来重用同一个进程setCommands()
,但是在第一次调用之后,进程的 OutputStream 被out.writeBytes("exit\n");
语句关闭。如果我评论这一行,似乎out.flush()
开始没有效果。有人可以向我解释为什么会发生这种情况以及如何正确地做到这一点?