Search code examples
c++linuxqtshellcode

Qt: Failed to find out application pid when run from binary using script


I have an aim to obtain the PID of application, when the latter runs. I wrote a simple function calls pgrep command:

QString Scriptlauncher::getAppProcessId() {
    QProcess p;
    QString programme("pgrep");
    QStringList args = QStringList() << "app_name";
    p.start(programme, args);
    p.waitForReadyRead();
    QByteArray rdata = p.readAllStandardOutput();
    qDebug() << "------------- script output rawdata is:" << rdata;
    if (!rdata.isEmpty()) {
        QString pid(rdata);
        pid = pid.left(pid.length() -1); // cut '\n' symbol
        qWarning() << "APPLICATION pid is" << pid;
        return pid;
    }
    qWarning() << "failed to find out PID";
    return ("-1");
}

When I run the program directly from Qt or using a simple script (call it execute.sh; it exports all needed shared libs and then run app binary, - to run the app from terminal), the codeblock from above returns correct value:

user@host:/standalone_package/ execute.sh
------------- script output rawdata is: "21094\n"
APPLICATION pid is "21094"

But when I run execute.sh from the valgrind heap profiler command, the function returns:

user@host:/standalone_package/ valgrind --tool=massif --trace-children=yes ./execute.sh
------------- script output rawdata is: ""
failed to find out PID

Solution

  • Thanks to Hayt for links! I've found a solution!

    The second link offered requires the instance of QProcess object. I have no idea about how to get it.

    But using first link, I get the code working both directly from app and under valgrind:

    QString Scriptlauncher::getAppProcessId() {
        long pid = (long)getpid();
        qDebug ("------------- pid is %d", pid);
        QString pidstr = QString::number(pid);
        return pidstr;
    }