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.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
MistyD
  • 16,373
  • 40
  • 138
  • 240
  • 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. – Frank Osterfeld Feb 06 '14 at 07:00
  • Here is what i tried `QProcess::startDetached("cmd.exe ", QStringList() << " /c " << " net " << " stop " << " \"MyService\"");` and it isnt working – MistyD Feb 06 '14 at 07:42
  • @MistyD: Try it without all the extra spaces, just like Frank suggested. – Mike Seymour Feb 06 '14 at 08:01
  • I tried it - unfortunatly it does not work – MistyD Feb 06 '14 at 08:05

1 Answers1

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\"");
TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
  • The second example should read: `QProcess::startDetached("cmd /c \"net stop \\\"MyService\\\"\"");` (mind the extra escapes inside the parameter string) – Martin Hennings Mar 21 '18 at 08: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](https://stackoverflow.com/a/66145732/2398993) – lvr123 Sep 06 '22 at 10:52