Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a cmd command using QProcess?

Tags:

c++

qt

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.

like image 807
MistyD Avatar asked Feb 06 '14 06:02

MistyD


1 Answers

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\"");
like image 99
TheDarkKnight Avatar answered Sep 28 '22 05:09

TheDarkKnight