簡述
前幾節里,分享了進程通信的幾種方式:Windows消息機制、Shared Memory(共享內存),本節講解下關於進程通信的另外一種方式-QProcess。
命令行參數啟動
說明
進程A-帶參啟動進程B
- 一般編寫程序時,嚴格來說,啟動外部程序,需要判斷版本是debug還是release。否則,有可能會造成錯誤。
- 判斷將要啟動的進程是否存在,如果不存在,則啟動;否則,不啟動。
- 傳參:這里我列舉的是json格式。
實現
void onSendMessage() { QString strExe(""); if (m_pProcess == NULL) m_pProcess = new QProcess(this); #if defined(QT_DEBUG) strExe = "ReceiveMessaged.exe"; # else strExe = "ReceiveMessage.exe"; # endif // 判斷進程是否存在 QProcess tasklist; tasklist.start("tasklist", QStringList() << "/NH" << "/FO" << "CSV" << "/FI" << QString("IMAGENAME eq %1").arg(strExe)); tasklist.waitForFinished(); QString strOutput = tasklist.readAllStandardOutput(); if (!strOutput.startsWith(QString("\"%1").arg(strExe))) { QJsonObject json; json.insert("UserName", QStringLiteral("╰☆一去、二三里`")); json.insert("Password", "123456"); QJsonDocument document; document.setObject(json); QByteArray byteArray = document.toJson(QJsonDocument::Compact); QStringList arguments; arguments << byteArray; m_pProcess->startDetached(strExe, arguments); } }
命令行讀取
說明
進程B-命令行讀取
- 在main函數中初始化QApplication以后,獲取命令行參數。
- 命令行參數中包含當前程序的名稱、接收的參數等信息。
實現
QStringList cmdLineArgs = QCoreApplication::arguments(); QMessageBox::information(NULL, QStringLiteral("ReceiveMessage"), cmdLineArgs.join(" "));
更多參考
原文作者:一去丶二三里
作者博客:去作者博客空間
