How to execute a cmd command using QProcess?

前端 未结 1 1891
心在旅途
心在旅途 2021-01-13 11:38

I am attempting to execute a cmd command using

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

This does not seem to stop t

1条回答
  •  天涯浪人
    2021-01-13 12:05

    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\"");
    

    0 讨论(0)
提交回复
热议问题