PDA

View Full Version : Start a linux command and read its standard output using QProcess



arunkumaraymuo
28th October 2015, 12:04
I am trying to read the output of a linux command using QProcess but its not given the correct output.


QProcess process;

process.start("iwconfig 2>&1 | grep ESSID");
process.waitForFinished();
usleep(1000);
QString output(process.readAllStandardOutput());
qDebug()<<output;

QString err(process.readAllStandardError());
qDebug()<<err;


In this code the qDebug()<<output; prints "" and
qDebug()<<err; prints "iwconfig: unknown command "|"
"
When I run this same command "iwconfig 2>&1 | grep ESSID" in terminal window its shown
wlan0 IEEE 802.11bgn ESSID:"Arun Kumar" Nickname:"<WIFI@REALTEK>"

Why my program printing "iwconfig: unknown command "|"", what is the error in my code and how I can correct this in my code?

anda_skoa
28th October 2015, 12:24
What you are trying to do is to run two programs, one piping output into the others input by using a shell pipe redirection.

This is a feature provided by shells, e.g. bash, dash, zsh.

So you can either run a script that does that in a shell context, run two processes and piping output from one to the other, or simply just run the first command and filter in your program.

Cheers,
_

arunkumaraymuo
29th October 2015, 05:22
Thanks to your reply.

I solved the issue by updating the code to
process.start("sh", QStringList()<<"-c"<<"iwconfig 2>&1 | grep ESSID");

jefftee
29th October 2015, 05:39
Write a small shell script that does exactly what you want, then execute the shell script using QProcess. For example, to take your original example, I'd write a small shell script named /path/to/test.sh as follows:



#!/bin/sh
iwconfig 2>&1 | grep ESSID
exit $?

Then execute QProcess as follows:



QProcess process;
process.start("/path/to/test.sh");
process.waitForFinished();
QString output = process.readAllStandardOutput();
qDebug() << output;
QString err = process.readAllStandardError();
qDebug() << err;

Of course you should add error checking, but that's the general gist of what anda_skoa is saying for one of the options he listed... You could also use two QProcess's where stdout from the 1st is piped to the 2nd QProcess's stdin, etc. Several options here, choose what's easiest for you to implement.

Good luck.