Question

I am developing a windows form application with Qt 5.0.2. I need to call another program during mine, which is a console application. I want to pass the arguments through command line or a file, and read the expecting results via another file, but, because of some reasons I need to when the program finishes its work and the expecting file is ready to be read.
My process is defined as follow :

QProcess *p;  
p = new QProcess(this);  
QStringList args;
args << "babak" << "Ali" << "Mohsen";
p->execute("ConsoleApplicationCSH.exe" ,args)

I know I could use start instead of execute, but the result was the same. I tried to check it out through this code:

while(!p->waitForFinished()){
    ;
}
exit(1);

The called is written is way that it takes around 10 sec to finishes it process, but the while loop does not finishes. I checked the other form of using this method and some similar methods but I didn`t get any good result.

Was it helpful?

Solution

First, you need to use QProcess::start() instead of QProcess::execute(): execute() is a static method running the process and blocking until it's done. So the process is already finished when execute() returns. Use start() to run the process without blocking.

Then, in GUI code, you should connect to the finished() and error() signals to learn about both successful termination and errors (check errorString() in case of errors).

If run in the main thread, waitForFinished() blocks the UI, thus it's usually undesirable to use the blocking calls. Note that waitForFinished() returns false not only on timeout, but "if the operation timed out, if an error occurred, or if this QProcess is already finished". Connecting to finished() and error() is a more robust way to detect error cases. If you really want to it in a blocking way (e.g. in a secondary thread or in a non-GUI program), call QProcess::waitForStarted() first, to detect cases where the process couldn't even be started more cleanly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top