Piping (or command chaining) with QProcess

Konstantin Ivanov picture Konstantin Ivanov · Jan 3, 2014 · Viewed 17.4k times · Source

I'm using Qt and bash over it, need to execute something like:

bash: cat file | grep string

in Qt:

QString cmd = "cat file | grep string";
QProcess *process = new QProcess;
process->start(cmd);
process->waitForBytesWritten();
process->waitForFinished();
qDebug() << process->readAll();

The problem is in pipe ("|"), and process returs nothing. If there is no ("|"), like

"cat file" 

everything is ok. I tried smth. like

"cat file \\| grep string", 
"cat file \| grep string" 

but result is the same. If I copy the command and run it in bash everything is ok.

QString::toAscii().data()

and other transforms also have bad result.

Answer

Dmitry Markin picture Dmitry Markin · Jan 3, 2014

The problem is you cannot run a system command with QProcess, but only a single process. So the workaround will be to pass your command as an argument to bash:

process.start("bash", QStringList() << "-c" << "cat file | grep string");