2017-07-03 60 views
-1

我試圖使用QProcess中獲得的記憶,我使用的是RedHat 7.3,如果我打開一個終端輸入免費,這給了我:Qt的QProcess中獲取內存信息

  total  used  free  shared buff/cache available 
Mem:  7865728  1602988  3984928  297040  2277812  5552268 
Swap:  8126460   0  8126460 

我試着產生相同的QT:

QProcess p; 
p.start("free"); 
p.waitForFinished(); 
QString strMemory = p.readAllStandardOutput(); 
qDebug() << strMemory; 
p.close(); 

然而,這並不工作,我的應用程序掛起,我也試着:

sh free 

沒有好轉。

+0

你嘗試'在/ usr/bin中/ free' – drescherjm

+0

只是去嘗試,起動過程中,當不幸的是相同的,應用程序掛起。 – SPlatten

+0

您可能還想對'waitForFinished()'進行時間限制並檢查進程的狀態。 – drescherjm

回答

0

多玩弄我發現啓動子進程外工作的IDE而不是從內它之後。

0

嘗試這樣:

const QString command { "free" }; 

QProcess p {}; 
p.start(command); 
if (!p.waitForFinished(-1)) 
{ 
    qWarning() << "Error:" << p.readAllStandardError(); 
    return; 
} 

const auto& output = p.readAllStandardOutput(); 
qDebug() << "Output:" << output; 
+0

這真的和我原來的代碼沒什麼不同。 – SPlatten

+0

@SPlatten:好吧,有一些變化,例如無限超時,檢查錯誤並打印'stderr'。順便說一句,你測試了嗎? – Azeem

+0

我測試過它,因爲我在原始文章中的新評論顯示,是的,它在IDE之外工作,但不在我的原始代碼中。 – SPlatten

-1

您正在使用同步API錯誤。嘗試非同步之一:

QProcess p; 
QString strMemory; 
QObject::connect(&p,&QProcess::readyReadStandardOutput,[&strMemory,&p]()->void{strMemory += QString::fromLatin1(p.readAllStandardOutput());}); 
QObject::connect(&p,&QProcess::readyReadStandardError,[&strMemory,&p]()->void{strMemory += QString::fromLatin1(p.readAllStandardError());}); 
QObject::connect(&p,static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),[&strMemory]()->void{qDebug() << strMemory;}); 
p.start("free"); 
+0

嘗試過你提出的解決方案,其結果是相同的,它不會從IDE中的工作和我原來的解決方案不一樣,我懷疑它會一樣礦IDE之外工作。 – SPlatten

+0

另一個問題是對象p的作用域在它完成之前會被銷燬,除非'p'是全局或靜態的。 – SPlatten

+0

@SPlatten生命週期可以輕鬆管理。只需在堆上分配並將完成的信號連接到deleteLater插槽即可。這是一個小小的更正 – IlBeldus