KGCybeX KGCybeX - 1 year ago 398
C++ Question

qt run shell commands via qprocess

I am developing a small QT application to interact with the terminal, to send commands to the terminal and to read back information printed out.

Example: get output of all processes using

ps -aux


I am able to write information out to the terminal but I dont think it is in the system scope, actual example:

Command passed to shell interpreter :
"echo "pre"; ps -aux; echo "post"

edit from comment:

I need to send specific complete commands, I am not looking for shortened or alternative commands, I require a method of sending a command like this :
ps -aux | grep chrome | tr -s " " | cut -d " " -f 2
and reading its output. This example is getting all pid's of all running chrome processes

Interpreters attempted :

  • sh

  • /bin/bash


QProcess *proc_ovpn = new QProcess(this);
proc_ovpn->start("sh",QStringList() << "-c" << "echo \"pre\";ps -aux; echo \"post\"");
QString str(proc_ovpn->readAllStandardOutput());
return str; <<< ======= //breakpoint here

Debug information:

When breakpoint is reached, debug information as follows:

str "" QString
this @0x555555ad7be0 Interface
Return Value
10000000 10000000 int

It was suggested to run shell code using this method above from a post on SO, could not find it again.

I am at a loss, I do not understand why running these commands to not interact directly with the system (and its information),

Any advice?

Answer Source

you need to use waitForFinished() after start, not before

proc_ovpn->start("sh",QStringList() << "-c" << "echo \"pre\";ps -aux; echo \"post\"");

this will blocks until the process has finished ...

Also, you may check if the process is started successfully and/or if waitForFinished timed out

proc_ovpn->start("sh",QStringList() << "-c" << "echo \"pre\";ps -aux; echo \"post\"");

if(!proc_ovpn->waitForStarted()) //default wait time 30 sec
    qWarning() << " cannot start process ";

int waitTime = 60000 ; //60 sec
if (!proc_ovpn->waitForFinished(waitTime))
         qWarning() << "timeout .. ";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download