我在Qt编写程序,目前使用popen运行linux命令并将输出读入字符串:
QString Test::popenCmd(const QString command) {
FILE *filePointer;
int status;
int maxLength = 1024;
char resultStringBuffer[maxLength];
QString resultString = "";
filePointer = popen(command.toStdString().c_str(), "r");
if (filePointer == NULL) {
return 0;
}
while (fgets(resultStringBuffer, maxLength, filePointer) != NULL) {
resultString += resultStringBuffer;
}
status = pclose(filePointer);
if (status == 0) {
return resultString;
} else {
return 0;
}
}
所以我想抛弃上面的代码,因为我更愿意使用Qt提供的更高级别的设施。有没有人有一个如何用QProcess做这个的例子,或者至少知道如何做到这一点?
对于它的价值,这将在Linux上运行。
谢谢
答案 0 :(得分:1)
这样做:
void Process::runCommand(const QString &p_Command) {
QProcess *console = new QProcess();
console->connect(console, SIGNAL(readyRead()), this, SLOT(out()));
console->connect(console, SIGNAL(finished(int)), this, SLOT(processFinished(int)));
console->start(p_Command);
}
void Process::out() {
QProcess *console = qobject_cast<QProcess*>(QObject::sender());
QByteArray processOutput = console->readAll();
}
void Process::processFinished(int p_Code) {
QProcess *console = qobject_cast<QProcess*>(QObject::sender());
QByteArray processOutput = console->readAll() + QString("Finished with code %1").arg(p_Code).toLatin1();
}
信号QProcess::finished()
可用于获取流程的退出代码。