8

few days ago i asked about how to get all running processes in the system using QProcess. i found a command line that can output all processes to a file:

C:\WINDOWS\system32\wbem\wmic.exe" /OUTPUT:C:\ProcessList.txt PROCESS get Caption

this will create C:\ProcessList.txt file contains all running processes in the system. i wonder how can i run it using QProcess and take its output to a variable.

it seems every time i try to run it and read nothing happens:

QString program = "C:\\WINDOWS\\system32\\wbem\\wmic.exe";
QStringList arguments;
arguments << "/OUTPUT:C:\\ProcessList.txt" <<"PROCESS"<< "get"<< "Caption";

process->setStandardOutputFile("process.txt");
process->start(program,arguments);

QByteArray result = process->readAll();

i prefer not to create process.txt at all and to take all the output to a variable...

sashoalm
  • 75,001
  • 122
  • 434
  • 781
kaycee
  • 1,199
  • 4
  • 24
  • 42
  • Kaycee -- I voted to close thinking this was not a question, but a closer read I see that it actually is. My bad. – Brian MacKay Apr 13 '10 at 19:37
  • You have `wmic` sending output to `c:\ProcessList.txt` and you redirect `wmic`'s standard output to `process.txt`. Which output are you trying to store in a variable? – Kaleb Pederson Apr 13 '10 at 19:55
  • i would like to store all the file output lets say in a map... file output is as the following: services.exe C:\Windows\system32\services services2.exe C:\Windows\system32\services services3.exe C:\Windows\system32\services . . . but for some reason only first line is saved... – kaycee Apr 13 '10 at 20:14

2 Answers2

8

You can run wmic.exe with "/OUTPUT:STDOUT" switch to print the process info directly to stdout. However, I was unable to read this info through QProcess API and save it in variable. Here's the code I used:

#include <QtCore/QCoreApplication>
#include <QProcess>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QProcess process;
    process.setReadChannel(QProcess::StandardOutput);
    process.setReadChannelMode(QProcess::MergedChannels);
//    process.start("cmd.exe /C echo test");
    process.start("wmic.exe /OUTPUT:STDOUT PROCESS get Caption");

    process.waitForStarted(1000);
    process.waitForFinished(1000);

    QByteArray list = process.readAll();
    qDebug() << "Read" << list.length() << "bytes";
    qDebug() << list;
}

This code successfully captures output of "cmd.exe /C echo test", but doesn't work on wmic.exe. It seems that process wmic.exe is never finished, and I suppose it's stdout is never flushed so you don't receive anything throught QProcess::readAll().

That's all help I can give you. Maybe you, or some other SO user will find bug in the snippet above.

chalup
  • 8,358
  • 3
  • 33
  • 38
2

Try this it will work well.

process.start("cmd", QStringList() << "/C" << "echo" << "process" << "get" << "caption" << "|" << "wmic");
bluish
  • 26,356
  • 27
  • 122
  • 180