I'm supposed to check whether the service is RUNNING
. I've a problem with QProcess
query execution, when it comes to executing the following query: SC QUERY "service name" | findstr RUNNING
, though this works fine when executed directly in command line in Windows. The code snipet here as follows:
QProcess process;
process.setProcessChannelMode(QProcess::ForwardedChannels);
process.start("SC QUERY \"Service_name\" | findstr RUNNING", QIODevice::ReadWrite);
// Wait for it to start
if(!process.waitForStarted())
return 0;
QByteArray buffer;
while(process.waitForFinished())
buffer.append(process.readAll());
qDebug() << buffer.data();
Output is:
Can you help me?
It is because using these three lines will not give you the expected results:
QProcess process;
process.setProcessChannelMode(QProcess::ForwardedChannels);
process.start("SC QUERY \"Service_name\" | findstr RUNNING", QIODevice::ReadWrite);
Based on the official documentation, QProcess
is supposed to work for pipe'd commands:
void QProcess::setStandardOutputProcess(QProcess * destination)
Pipes the standard output stream of this process to the destination process' standard input.
In other words, the command1 | command2
shell command command can be achieved in the following way:
QProcess process1;
QProcess process2;
process1.setStandardOutputProcess(&process2);
process1.start("SC QUERY \"Service_name\"");
process2.start("findstr RUNNING");
process2.setProcessChannelMode(QProcess::ForwardedChannels);
// Wait for it to start
if(!process1.waitForStarted())
return 0;
bool retval = false;
QByteArray buffer;
while ((retval = process2.waitForFinished()));
buffer.append(process2.readAll());
if (!retval) {
qDebug() << "Process 2 error:" << process2.errorString();
return 1;
}
qDebug() << "Buffer data" << buffer;