Start a linux command and read its standard output using QProcess
I am trying to read the output of a linux command using QProcess but its not given the correct output.
Code:
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?
Re: Start a linux command and read its standard output using QProcess
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,
_
Re: Start a linux command and read its standard output using QProcess
Thanks to your reply.
I solved the issue by updating the code to
Code:
process.
start("sh",
QStringList()<<
"-c"<<
"iwconfig 2>&1 | grep ESSID");
Re: Start a linux command and read its standard output using QProcess
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:
Code:
#!/bin/sh
iwconfig 2>&1 | grep ESSID
exit $?
Then execute QProcess as follows:
Code:
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.