Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a shell command under Linux unsing QProcess?

I am trying to read the screen resolution from within a Qt application, but without using the GUI module.

So I have tried using:

xrandr |grep \* |awk '{print $1}'

command through QProcess, but it shows a warning and does not give any output:

unknown escape sequence:'\\*'

Rewriting it with \\\* does not help, as it leads to the following error:

/usr/bin/xrandr: unrecognized option '|grep'\nTry '/usr/bin/xrandr --help' for more information.\n

How can I solve that?

like image 281
Som Avatar asked Aug 04 '26 07:08

Som


2 Answers

You have to use bash and pass the argument in quotes:

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QProcess process;
    QObject::connect(&process, &QProcess::readyReadStandardOutput, [&process](){
       qDebug()<<process.readAllStandardOutput();
    });
    QObject::connect(&process, &QProcess::readyReadStandardError, [&process](){
       qDebug()<<process.readAllStandardError();
    });
    process.start("/bin/bash -c \"xrandr |grep \\* |awk '{print $1}' \"");
    return a.exec();
}

Output:

"1366x768\n"

Or:

QProcess process;
process.start("/bin/bash", {"-c" , "xrandr |grep \\* |awk '{print $1}'"});

Or:

QProcess process;
QString command = R"(xrandr |grep \* |awk '{print $1}')";
process.start("/bin/sh", {"-c" , command});
like image 142
eyllanesc Avatar answered Aug 05 '26 22:08

eyllanesc


You can't use QProcess to execute piped system commands like that, it is designed to run a single program with arguments Try:

QProcess process;
process.start("bash -c xrandr |grep * |awk '{print $1}'");

OR

QProcess process;
QStringList args = QString("-c,xrandr,|,grep *,|,awk '{print $1}'").split(",");
process.start("bash", args);
like image 31
Marker Avatar answered Aug 05 '26 22:08

Marker