5

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.

4
  • 1
    Try startDetached("cmd", QStringList() << "/c" << "net" << "stop" << "MyService"); and the same with << "\"MyService\"". For further debugging, don't use startDetached but start and connect to the QProcess instance's finished() and error() signals. Feb 6, 2014 at 7:00
  • Here is what i tried QProcess::startDetached("cmd.exe ", QStringList() << " /c " << " net " << " stop " << " \"MyService\""); and it isnt working
    – MistyD
    Feb 6, 2014 at 7:42
  • @MistyD: Try it without all the extra spaces, just like Frank suggested. Feb 6, 2014 at 8:01
  • I tried it - unfortunatly it does not work
    – MistyD
    Feb 6, 2014 at 8:05

1 Answer 1

6

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\"");
2
  • The second example should read: QProcess::startDetached("cmd /c \"net stop \\\"MyService\\\"\""); (mind the extra escapes inside the parameter string) Mar 21, 2018 at 8:50
  • Not working for me and not required. In a mkdir example, this is enough: proc.start("cmd /c mkdir \"c:/temp/foo bar9\""). See this question
    – lvr123
    Sep 6, 2022 at 10:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.