• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Help Execute a shell command as root from C++ on Android

I want to execute a shell command from C++ on my android phone as root. My device is rooted. I compile for arm64-v8a and armeabi-v7s. I run my program as root.

I currently use this function to execute the command and get back the result :

std::string execAndGetResult(const char* cmd) {
std::array<char, 128> buffer;
std::string result = "";
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) {

printf("ERROR PIPE");
return result;
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {

result += buffer.data();
}
return result;
}

For example I use the current call :

execAndGetResult("touch foo");

If I run my program as non root user, everything works fine. But as soon as I run it as root user, only the program compile for armeabi-v7s works.

For arm64-v8a, the only thing I am able to get back is the error code 32512 which correspond to 127 (error from touch).

I tried to execute different commands :

execAndGetResult("/system/bin/touch foo");
execAndGetResult("/system/bin/touch /data/local/tmp/foo");
execAndGetResult("/system/bin/touch foo 2>bar");


None of them worked. Even the last one don't do anything.
 
Back
Top Bottom