简体   繁体   English

Java:在读取进程的InputStream之前等待进程的子进程完成

[英]Java: Wait for subprocess of process to finish before reading process's InputStream

I have a process created as follows: 我有一个创建如下的过程:

Process p = Runtime.getRuntime().exec(new String[]{"su"});

In my program, I only want to create this process once. 在我的程序中,我只想创建一次此过程。 I am developing a root file explorer application for Android, and whenever this process is created, the Android device will prompt the user to grant root permissions. 我正在为Android开发一个根文件资源管理器应用程序,每当创建此过程时,Android设备将提示用户授予root权限。 This is a very slow operation, and as this is a file browser, it will need root permissions often. 这是一个非常慢的操作,因为这是一个文件浏览器,它经常需要root权限。 So, I have decided to create this process once and write commands to its OutputStream in the following manner (stdin is this OutputStream): 所以,我决定一次创建这个进程,并以下面的方式将命令写入其OutputStream(stdin是这个OutputStream):

stdin.writeBytes(command + "\n");

Before I can read the output of the command, I need my program to wait until the command written by writeBytes has terminated. 在我可以读取命令的输出之前,我需要我的程序等到 writeBytes 写入的命令 终止。 I have tried p.waitFor() , but this causes the program to hang. 我试过p.waitFor() ,但这导致程序挂起。

Here is how I read bytes from the InputStream: 以下是我从InputStream中读取字节的方法:

int read;
String out = "";
stdout = p.getInputStream();
byte[] buffer = new byte[262144];

while (true) {
    read = stdout.read(buffer);
    out += new String(buffer, 0, read);
    if (read < BUFF_LEN) {
        //we have read everything
        break;
    }
}

Note that although the read(buffer) method blocks until input data is available, it does not block in this case because it thinks it has reached the end of the InputStream. 请注意,尽管read(buffer)方法会阻塞直到输入数据可用,但在这种情况下它不会阻塞,因为它认为它已到达InputStream的末尾。

I have tried to include only relevant portions of my code in this post, but if you would like to take a look at the entire source code of the class where this is contained, see here: http://pastebin.com/t6JdWmQr . 我试图在这篇文章中仅包含我的代码的相关部分,但是如果你想查看包含它的类的完整源代码,请参见此处: http//pastebin.com/t6JdWmQr

How can I make sure the command has finished running before reading the process' InputStream? 在读取进程'InputStream之前,如何确保命令已完成运行?

I also encounter similar problem, and I found the answer here: Wait until a command in su finishes 我也遇到类似的问题,我在这里找到答案: 等到su中的命令完成

If you don't need any read stream in this shell process, simply add shell read stream may completed the shell process. 如果在这个shell进程中不需要任何读取流,只需添加shell读取流即可完成shell进程。

Or in XDA also have better way: [HowTo]Execute Root Commands and read output 或者在XDA中也有更好的方法: [HowTo]执行Root命令和读取输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM