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...

4

2 回答 2

8

您可以使用“/OUTPUT:STDOUT”开关运行 wmic.exe,将进程信息直接打印到标准输出。但是,我无法通过 QProcess API 读取此信息并将其保存在变量中。这是我使用的代码:

#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;
}

此代码成功捕获“cmd.exe /C echo test”的输出,但不适用于 wmic.exe。似乎进程 wmic.exe 永远不会完成,我想它的标准输出永远不会被刷新,所以你不会通过 QProcess::readAll() 收到任何东西。

这就是我能给你的所有帮助。也许您或其他一些 SO 用户会在上面的代码段中发现错误。

于 2010-04-13T20:50:24.167 回答
2

试试这个,它会很好用。

process.start("cmd", QStringList() << "/C" << "echo" << "process" << "get" << "caption" << "|" << "wmic");
于 2010-11-08T10:11:37.633 回答