Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a shell command via QProcess on Android Platform

I cannot run any command via QProcess on Android platform. I am using Qt library. Can anyone explain how to run shell commands from my application on Android platform ?

    QProcess process();

    process.execute("ls");

   bool finished = process.waitForFinished(-1);

   qDebug() <<  "End : " << finished << " Output : " << process.errorString();

The process doesn't finish if I don't specify timeout. process.waitForFinished() returns false when I specify timeout let's say 10000 ms.

like image 346
arnes Avatar asked Jan 19 '17 07:01

arnes


2 Answers

Your example code is faulty and it will not work on ANY platform! ls command is not an exactable! This command is build into a shell program for example bash.

Another bug in your code is that QProcess::execute is a static function. So final line doesn't have impact on process you have tried to start.

So your code should look like this:

QProcess process;
process.start("bash", QStringList() << "-c" << "ls");

bool finished = process.waitForFinished(-1);
like image 161
Marek R Avatar answered Oct 05 '22 11:10

Marek R


You are using QProcess::execute() which is a static function. Quoting Qt documentation: "Starts the program command in a new process, waits for it to finish".

So what could happen in your code is:

QProcess process();

process.execute("ls"); // Start "ls" and wait for it to finish
// "ls" has finished
bool finished = process.waitForFinished(-1); // Wait for the process to finish, but there is no process and you could get locked here forever...

There are 2 ways to fix your code:

QProcess process();

process.start("ls"); // Start "ls" and returns

bool finished = process.waitForFinished(-1);

qDebug() <<  "End : " << finished << " Output : " << process.errorString();

or

 QProcess::execute("ls");
like image 33
Benjamin T Avatar answered Oct 05 '22 12:10

Benjamin T