尝试用这种方法给exec它:
private boolean performScript(String script) {
script = "mount -o rw remount /dev && touch /dev/test";
try {
// Executes the command.
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
os.writeBytes(script + "\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
// // Reads stdout.
// // NOTE: You can write to stdin of the command using process.getOutputStream().
// final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
// int read;
// final char[] buffer = new char[4096];
// while ((read = reader.read(buffer)) > 0) {
// stringBuilder.append(buffer, 0, read);
// txtInfo.setText(stringBuilder.toString());
// }
// reader.close();
// Waits for the command to finish.
process.waitFor();
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
这里的诀窍是运行脚本作为超级用户。
/dev不是普通文件的位置。用'touch'创建一个是一个错误。使用'mknod',但不要期望结果像普通文件一样运行。你究竟在做什么**来完成**? – 2015-04-06 12:49:53
我正在创建一个将写入文件并由设备驱动程序轮询的系统服务。 – Odin 2015-04-19 19:20:33
除了对任务使用错误的操作(如前所述,您必须使用带有适当的主号码和次号码以及设备类型而不是“touch”的'mknod'),您不会将其作为超级用户运行。每个对exec()的调用都是独立的 - 你调用su只会退出,然后尝试将其他命令作为应用程序的用户运行,而不是以root身份运行。 – 2015-04-19 20:25:22