廣義上,所有 I/O 均為數據交互。Linux 將設備抽象為文件,進程間通信本質也是文件操作。Qt 提供 QProcess 類封裝底層差異,讓我們能像操作文件一樣啟動外部程序、傳遞參數、讀取輸出。典型場景:調用系統命令(dir/ls)、調用 SVN 獲取版本號生成 Build Number、啟動輔助進程等。
最簡單用法——點擊按鈕啟動記事本:
// mainwindow.h
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
private slots:
void openProcess();
private:
QProcess *p;
};
// mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
p = new QProcess(this);
QPushButton *bt = new QPushButton("execute notepad", this);
connect(bt, SIGNAL(clicked()), this, SLOT(openProcess()));
}
void MainWindow::openProcess() {
p->start("notepad.exe"); // 系統路徑已包含,無需完整路徑
}
QProcess::start() 參數:program(可執行文件)、arguments(QStringList 類型參數列表)。
調用 cmd.exe /c dir(Windows)或 ls(Linux),異步讀取標準輸出:
void MainWindow::openProcess() {
#if defined(Q_OS_WIN32)
p->start("cmd.exe", QStringList() << "/c" << "dir");
#elif defined(Q_OS_LINUX)
p->start("ls", QStringList() << "/home/usr_name");
#endif
connect(p, SIGNAL(finished(int)), this, SLOT(readResult(int)));
}
void MainWindow::readResult(int exitCode) {
if (exitCode == 0) {
#if defined(Q_OS_WIN32)
QTextCodec *gbkCodec = QTextCodec::codecForName("GBK");
QString result = gbkCodec->toUnicode(p->readAll());
#elif defined(Q_OS_LINUX)
QTextCodec *utfCodec = QTextCodec::codecForName("UTF-8");
QString result = utfCodec->toUnicode(p->readAll());
#endif
QMessageBox::information(this, "dir", result);
}
}
關鍵點:
finished(int) 信號攜帶退出碼,0 表示正常結束readAll() 返回 QByteArray,需按平台編碼(Windows GBK / Linux UTF-8)轉 QStringQ_OS_WIN32/Q_OS_LINUX 實現編譯期平台隔離QProcess 還支持:
waitForStarted()/waitForFinished() 同步等待setProcessChannelMode() 合併/分離標準輸出與錯誤輸出QProcessEnvironment 注入環境變量readAllStandardOutput()/readAllStandardError()QProcess 以統一介面屏蔽平台差異,是 Qt 跨平台 IPC 的基石。善用預處理宏處理平台專屬邏輯,優先使用 Qt 標準 API 減少 #ifdef 散佈,代碼更清晰可維護。