如何在 Android 上获取失败的 shell 命令的错误消息
在已 root 的 Android 设备上,我尝试运行 cat 命令来读取内核日志,如下所示:
Process p = Runtime.getRuntime().exec("su");
p = Runtime.getRuntime().exec("/system/bin/cat /proc/kmsg");
su 命令已成功执行,但 cat 未执行。 我尝试使用 getInputStream() 读取命令的输出,但什么也没有,如下所示:
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((read = err.read(buffer)) > 0)
{ //read error to buffer
catOutput.append(buffer, 0, read);
}
in.close();
我使用与 ls 命令相同的代码而不是显示内核日志,它工作得很好并向我显示结果。
我想知道在执行 cat 命令时我是否遇到了什么错误并希望在 shell 上查看错误消息。尝试了 p.getErrorStream() 但它没有给我任何结果。 有人可以帮我解决这个问题吗?谢谢。
On a rooted android device, I tried to run a cat command that read kernel log, as follow:
Process p = Runtime.getRuntime().exec("su");
p = Runtime.getRuntime().exec("/system/bin/cat /proc/kmsg");
The su command was successfully executed but not the cat.
I tried to read the output of the command using getInputStream() but nothing was there, as follow:
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((read = err.read(buffer)) > 0)
{ //read error to buffer
catOutput.append(buffer, 0, read);
}
in.close();
I used the same code with ls command instead of displaying the kernel log, it worked just fine and show me the result.
I wonder if what error I am getting and wantted to see the error message on the shell when executing the cat command. Tried the p.getErrorStream() but it doesn't give me any result.
Could any one help me with this ? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个关于如何执行此操作的综合示例 - 请注意,我从这个答案中得到了这个想法:
Here's a comprehensive example on how to do this - note that I got the idea from this answer:
我终于通过使用 RootTools 库找到了问题的解决方案。
最近发布(在我提出问题几个月后),RootTools 提供了一个易于使用的工具帮助运行需要 root 权限的命令的工具集。我创建了一个包装器来在执行 shell 命令之前检查 root 访问权限是否可用:
函数调用的示例如下:
注意:该工具还支持同时运行多个命令。
I finally found the solution for the problem by using RootTools library.
Recently released (few months after my question was asked), RootTools provides a easy-to-use tool set that helps running commands that required root privilege. I created a wrapper to check if root access is available before executing shell command:
An example of a function call is:
Note: The Tool also support running multiple commands at once.