阅读苏进程中命令的输出 [英] Read command output inside su process

查看:111
本文介绍了阅读苏进程中命令的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我将present我的情况。 我需要在我的Andr​​oid应用程序执行su命令,效果很好。然后,我需要执行ls命令和读取输出。我通过获取从俗过程中的输出流,写我的命令把它做起来。

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 doing it by getting the output stream from the "su" process and writing my command into it.

和这里不用的问题。如何阅读LS过程的输出?我想说明的是苏Process对象。获取输入流,从它提供什么,因为苏不写任何东西。但是,LS不,我不知道如何访问它的输出消息。

And here goes the question. How to read the output of the "ls" process? All I have is the "su" Process object. Getting the input stream from it gives nothing, because "su" doesn't write anything. But "ls" does and I don't know how to access its output messages.

我已经搜查了许多网站,但我没有找到任何解决方案。也许有人会帮我:)

I have searched many sites but I didn't find any solution. Maybe someone will help me:)

问候

推荐答案

好吧,我已经找到了解决办法。它应该是这样的:

Ok, I've found a solution. It should look like this:

Process p = Runtime.getRuntime().exec(new String[]{"su", "-c", "system/bin/sh"});
DataOutputStream stdin = new DataOutputStream(p.getOutputStream());
//from here all commands are executed with su permissions
stdin.writeBytes("ls /data\n"); // \n executes the command
InputStream stdout = p.getInputStream();
byte[] buffer = new byte[BUFF_LEN];
int read;
String out = new String();
//read method will wait forever if there is nothing in the stream
//so we need to read it in another way than while((read=stdout.read(buffer))>0)
while(true){
    read = stdout.read(buffer);
    out += new String(buffer, 0, read);
    if(read<BUFF_LEN){
        //we have read everything
        break;
    }
}
//do something with the output

希望这将是有益的人。

Hope it will be helpful for someone

这篇关于阅读苏进程中命令的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆