Search code examples
androidrootsu

My application freezes after a superuser request


I am writing an application which involves getting information on all running processes (name/package name to begin with). I am doing this by invoking "ps" in my code. I requested superuser access from within the application before invoking the "ps" command. However, when I attempt to read the input stream, the application freezes and I do not get any output in the Logcat. Below is the code that I am using:

Process process = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(process.getOutputStream());
        outputStream.writeBytes("ps -t -x -P -p -c");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String topInfo = bufferedReader.readLine(); //Where it freezes
        while(topInfo != null)
        {
            Log.i(appInfo, topInfo);
            topInfo = bufferedReader.readLine();
        }
        outputStream.flush();
        outputStream.close();

The code works as expected without superuser request, however the result only consists of my application and the "ps" process.

Is there something that I have missed, or something I need to research before I attempt to fix this?I have tried to search this issue on the Internet before asking here, without success. Any help is appreciated.

Thanks in advance.

P.S The application is being run on a rooted device running Android 7.1.1


Solution

  • I have found the cause of the problem. As it turns out, the BufferedReader was not ready to read, therefore it was not getting any input from the input stream. I confirmed this with the following code:

            while(bufferedReader.ready())
            {
                String topInfo;
                while ((topInfo = bufferedReader.readLine()) != null)
                {
                    Log.i(appInfo, topInfo);
                }
            }
    

    The fix to this problem is to wait for the BufferedReader to be ready to to read the process input stream. This can either be done by pausing the thread for some time, or including a loop that will loop through till the BufferedReader is ready to read. I opted for the latter, as shown below:

            do
            {
                //Wait
            } while(!bufferedReader.ready());
    

    This gave me the desired results, which was a list of processes running on my device.