-1

I am trying to use QProcess to get the memory, I'm using RedHat 7.3, if I open a terminal and type free, this gives me:

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

I've tried to produce the same in QT:

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

However this doesn't work and my application hangs, I've also tried:

sh free

No better.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
SPlatten
  • 5,334
  • 11
  • 57
  • 128

3 Answers3

0

Try something like this:

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;
Azeem
  • 11,148
  • 4
  • 27
  • 40
0

After much playing around I found that the starting the a child process works outside of the IDE but not from within it.

SPlatten
  • 5,334
  • 11
  • 57
  • 128
-1

You are using the synchronous API wrong. try the asynch one:

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");
IlBeldus
  • 1,040
  • 6
  • 14
  • Having tried your proposed solution, the result is identical, it doesn't work from within the IDE and my original solution does the same, I suspect it will work outside of the IDE as does mine. – SPlatten Jul 04 '17 at 06:53
  • Another problem is that the scope of the object p will be destroyed before it completes unless 'p' is global or static. – SPlatten Jul 04 '17 at 07:20
  • @SPlatten lifecycle can be easily managed. just allocate on heap and connect finised signal to deleteLater slot. It's a trivial fix – IlBeldus Jul 04 '17 at 09:20
  • Still doesn't explain why it doesn't work in the IDE, I tried with: static QProcess p to get rid of the problem with it being destroyed. – SPlatten Jul 04 '17 at 09:23