【发布时间】:2012-04-21 13:22:28
【问题描述】:
在我的一生中,我无法让我的应用从 su shell 中调用 busybox 的进程获取响应。
我尝试了三种不同的方法,也尝试了这三种方法的组合以使其工作,但我永远无法使用busybox从任何东西中获得输出,只能从其余命令获得输出。
更具体地说,我可以让它返回像ls /data 和cat suchandsuch.file 这样的命令,但是任何以“busybox”开头的东西(即busybox mount,busybox free)都不会显示任何东西。
这是最适合我的方法,此代码适用于 ls /data,但不适用于“busybox free”
这个会运行命令(大部分情况下),并返回一个空字符串,而不是从输入流中无限循环。
Process p;
try {
p = Runtime.getRuntime().exec(new String[]{"su", "-c", "/system/bin/sh"});
DataOutputStream stdin = new DataOutputStream(p.getOutputStream());
stdin.writeBytes("ls /data\n");
DataInputStream stdout = new DataInputStream(p.getInputStream());
byte[] buffer = new byte[4096];
int read = 0;
String out = new String();
while(true){
read = stdout.read(buffer);
out += new String(buffer, 0, read);
if(read<4096){
break;
}
}
Toast.makeText(getApplicationContext(), out, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
底部附近的 toast 显示了来自 ls /data 的所有内容,但是当为busybox 更改为任何内容时,其为空白或 null。
我也尝试了这两种方法,但都没有奏效。 (我在命令运行后将进程传递给他们。)
当您点击方法按钮时,这两者都会导致应用程序冻结。
String termReader(Process process){
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
try {
int i;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((i = reader.read(buffer)) > 0)
output.append(buffer, 0, i);
reader.close();
return output.toString();
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
}
String processReader(Process process){
InputStream stdout = process.getInputStream();
byte[] buffer = new byte[1024];
int read;
String out = new String();
while(true){
try {
read = stdout.read(buffer);
out += new String(buffer, 0, read);
if(read<1024){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return out;
}
没有可使用的堆栈跟踪,所以我开始有点难过。
使用下面建议的代码进行编辑,嗯,下面:D 我对其进行了一些更改,使其成为一键运行的东西,以便于进行故障排除和测试。
当它尝试读取输入流时它也会冻结,如果我在尝试读取流之前调用stdin.writeBytes("exit\n"),它会给我关闭终端的空白答案,如果我在之后调用它,它会无限循环。
void Run() {
String command = "busybox traceroute\n";
StringBuffer theRun = null;
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream stdin = new DataOutputStream(process.getOutputStream());
stdin.writeBytes(command);
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
theRun = output.append(buffer, 0, read);
}
reader.close();
process.waitFor();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Toast.makeText(getApplicationContext(), theRun, Toast.LENGTH_SHORT).show();
}
它似乎跳过了第一行(每次调用命令时都会得到的 busybox 信息行)并且没有捕获其余数据。我已经尝试了我能想到的所有变体来让它正常工作:/
如果有人对此有所了解,我将不胜感激:)
【问题讨论】:
标签: android shell loops busybox su