MistyD
MistyD

Reputation: 17223

How to execute a cmd command using QProcess?

I am attempting to execute a cmd command using

QProcess::startDetached("cmd /c net stop \"MyService\"");

This does not seem to stop the service. However, if I run it from start >> run, it works.

Upvotes: 5

Views: 13683

Answers (1)

TheDarkKnight
TheDarkKnight

Reputation: 27611

QProcess::startDetached will take the first parameter as the command to execute and the following parameters, delimited by a space, will be interpreted as separate arguments to the command.

Therefore, in this case: -

QProcess::startDetached("cmd /c net stop \"MyService\"");

The function sees cmd as the command and passes /c, net, stop and "MyService" as arguments to cmd. However, other than /c, the others are parsed separately and are not valid arguments.

What you need to do is use quotes around the "net stop \"MyService\" to pass it as a single argument, so that would give you: -

QProcess::startDetached("cmd /c \"net stop \"MyService\"\"");

Alternatively, using the string list you could use: -

QProcess::startDetached("cmd", QStringList() << "/c" << "net stop \"MyService\"");

Upvotes: 6

Related Questions