简体   繁体   中英

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. This is a very slow operation, and as this is a file browser, it will need root permissions often. So, I have decided to create this process once and write commands to its OutputStream in the following manner (stdin is this 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. I have tried p.waitFor() , but this causes the program to hang.

Here is how I read bytes from the 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.

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 .

How can I make sure the command has finished running before reading the process' InputStream?

I also encounter similar problem, and I found the answer here: Wait until a command in su finishes

If you don't need any read stream in this shell process, simply add shell read stream may completed the shell process.

Or in XDA also have better way: [HowTo]Execute Root Commands and read output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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