【问题标题】:How to execute shell scripts with blktrace commands in android programmatically?如何以编程方式在android中使用blktrace命令执行shell脚本?
【发布时间】:2021-05-08 14:59:27
【问题描述】:

我有一个安装了 blktrace 的根 android 设备。我想从我的应用程序中执行一个 shell 脚本来测试 blktrace。我尝试了一些在互联网上的一些资源中找到的解决方案。这两种执行shell脚本的方法我都试过了

方法一

fun executeShell(): String {
    val output = StringBuffer()
    val p: Process
    try {
        p = Runtime.getRuntime().exec("path/to/script/file")
        p.waitFor()
        val reader =
            BufferedReader(InputStreamReader(p.inputStream))
        var line = ""
        while (reader.readLine().also { line = it } != null) {
            output.append(line + "n")
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return output.toString()
}

方法二

 private fun runAsRoot():Boolean {
    try {
        // Executes the command. /data/app/test.sh
        val process = Runtime.getRuntime().exec("path/to/shellscript/file")
        // Reads stdout.
        // NOTE: You can write to stdin of the command using
        //       process.getOutputStream().
        val reader = BufferedReader(
            InputStreamReader(process.inputStream)
        )
        var read: Int
        val buffer = CharArray(4096)
        val output = StringBuffer()
        while (reader.read(buffer).also { read = it } > 0) {
            output.append(buffer, 0, read)
        }
        reader.close()

        // Waits for the command to finish.
        process.waitFor()
        output.toString()
        Log.e("output", "OUT " + output.toString()).toString()
        isShellRun = true
       
    } catch (e: IOException) {
        isShellRun = false

        throw RuntimeException(e)
    } catch (e: InterruptedException) {
        isShellRun = false

        throw RuntimeException(e)
    }
    return isShellRun
}

这些方法适用于如下 shell 命令并显示预期输出

ls /sdcard/ 
cat /proc/cpuinfo

我想执行一些命令,例如blktrace -d /dev/block/sda -w 30 -D /sdcard/blktrace_app_runs,但它不能通过我的应用程序执行。但是我可以通过具有su root权限的adb shell完美地执行这个命令。

如何从我的应用程序中执行blktrace -d /dev/block/sda -w 30 -D /sdcard/blktrace_app_runs 之类的命令?

【问题讨论】:

    标签: android shell kotlin sh blktrace


    【解决方案1】:

    我认为您的命令需要类似这样的字符串数组。

        private static final String processId = Integer.toString(android.os.Process
                    .myPid());
        
       String[] command = new String[] { "logcat", "-d", "threadtime" };
       Process process = Runtime.getRuntime().exec(command);
    

    我的答案可以在这里找到:https://stackoverflow.com/a/37720611/3806413

    【讨论】:

      猜你喜欢
      • 2013-01-26
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 2011-03-21
      • 2014-05-17
      • 1970-01-01
      相关资源
      最近更新 更多