简体   繁体   中英

How to execute shell scripts with blktrace commands in android programmatically?

I have a rooted android device with blktrace installed in it. I want to execute a shell script for testing blktrace from my application. I have tried some solutions found in some resources from internet. I have tried these two methods for executing shell scripts

Method 1

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()
}

Method 2

 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
}

These methods works fine with shell commands like below and show expected outputs

ls /sdcard/ 
cat /proc/cpuinfo

I want to execute some commands like blktrace -d /dev/block/sda -w 30 -D /sdcard/blktrace_app_runs but it doesn't execute via my app. But I can execute this command perfectly via adb shell with su root permission.

How can I execute commands like blktrace -d /dev/block/sda -w 30 -D /sdcard/blktrace_app_runs from my app?

I think you need something like this array of strings for your command.

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

My answer can be found here: https://stackoverflow.com/a/37720611/3806413

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM