J.Steve
J.Steve

Reputation: 17

Calling multiple commands via system() under windows doesn't work

So basiclly im trying to use this:

int main()
    {
    
    system("adb kill-server \n"
                   "adb devices \n"
                   "adb start-server & \n"
                   "var=$(adb shell \"pidof com.rok\")\n"
                   "AFTER=`echo $var | sed 's/\\r//g'`\n"
                   "echo \"$AFTER\"\n"
                   "adb shell \"kill -STOP $AFTER\"\n"
                   "adb shell sleep 2\n"
                   "adb shell \"kill -CONT $AFTER\"");
                   
        return 0;
}

thing is this works in Clion without any error, but i must do this in visual studio and in visual studio i cannot do it like that i have to do every system command alone like:

        system("adb kill-server");
        system("adb devices");
        system("adb start-server");
        system("var=$(adb shell \"pidof com.rok\")");
        system("AFTER=`echo $var | sed 's/\\r//g'`");
        system("adb shell \"kill -STOP $AFTER\"");

so now the thing is when i run it like this everything works except this two lines:

        system("var=$(adb shell \"pidof com.rok\")");
        system("AFTER=`echo $var | sed 's/\\r//g'`");

even though they perfectly works on clion they dont in visual studio, i cannot find a way to solve this problem, this is the error:

'var' is not recognized as an internal or external command,

operable program or batch file.

'AFTER' is not recognized as an internal or external command,

operable program or batch file.

can anyone explain why this happens? and how can i solve this problem?

Upvotes: 1

Views: 257

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Each call of system() creates it's own shell as a subprocess, that's why multiple subsequent system() calls don't work if you e.g. try to set shell variables or do a cd command (expecting subsequent commands running in a specific directory).

The easiest way to do it, is to create a little temporary script file containing all the commands and execute this one with a single system() call:

// A raw string literal to make escaping easier 
// (see https://en.cppreference.com/w/cpp/language/string_literal)
std::string cmds = R"xxx(
adb kill-server
adb devices
adb start-server & 
var=$(adb shell "pidof com.rok")
AFTER=`echo $var | sed 's/\r//g'`
echo "$AFTER"
adb shell "kill -STOP $AFTER"
adb shell sleep 2
adb shell "kill -CONT $AFTER"
)xxx";

std::ofstream cmdFile("tempCmdFile.cmd");

cmdFile << cmds;
cmdFile.close();

system("tempCmdFile.cmd");

You probably should tidy up the tempCmdFile.cmd up afterwards (i.e. remove it). But I hope you grasp what the code above does.

Also I am not so sure that

AFTER=`echo $var | sed 's/\r//g'`

will work in a windows shell, as you expect it to do. You probably need a different solution for that, or a *nix like shell to run it (e.g. MinGw provides one).

Upvotes: 1

Related Questions