Read command output inside su process

后端 未结 3 735
余生分开走
余生分开走 2020-11-28 08:05

firstly I will present my situation. I need to execute \"su\" command in my android app and it works well. Then I need to execute \"ls\" command and read the output. I\'m do

3条回答
  •  余生分开走
    2020-11-28 08:15

    I modified accepted answer by @glodos for following problems:

    1. the streams are closed, otherwise the exec process hangs forever, on the opened stream. If you execute ps in shell (ie adb shell) after several executions then you'll see several su processes alive. They needs to be properly terminated.
    2. added waitFor() to make sure the process is terminated.
    3. Added handling for read=-1, now commands with empty stdout can be executed. Previously they crashed on new String(buffer, 0, read)
    4. Using StringBuffer for more efficient strings handling.

      private String execCommand(String cmd) throws IOException, InterruptedException {
          Process p = Runtime.getRuntime().exec(new String[]{"su", "-c", "system/bin/sh"});
          DataOutputStream stdout = new DataOutputStream(p.getOutputStream());
      
          stdout.writeBytes(cmd);
          stdout.writeByte('\n');
          stdout.flush();
          stdout.close();
      
          BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));
          char[] buffer = new char[1024];
          int read;
          StringBuffer out = new StringBuffer();
      
          while((read = stdin.read(buffer)) > 0) {
              out.append(buffer, 0, read);
          }
          stdin.close();
          p.waitFor();
          return out.toString();
      }
      

    Some credits go to @Sherif elKhatib ))

提交回复
热议问题