Qt - Wait for Qprocess to finish
15,199
Solution 1
You need to terminate the cmd.exe by sending exit
command, otherwise it will wait for commands
Here is my suggestion:
QProcess process;
process.start("cmd.exe");
process.write ("del f:\\b.txt\n\r");
process.write ("exit\n\r");
process.waitForFinished();
process.close();
Solution 2
The process you're starting is cmd.exe which, by itself will, not terminate. If you call cmd with arguments, you should achieve what you want: -
QProcess process;
process.start("cmd.exe \"del f:\\b.txt"\"");
process.waitForFinished();
process.close();
Note that the arguments are escaped in quotes.
Alternatively, you could call the del process, without cmd: -
QProcess process;
process.start("del \"f:\\b.txt"\"");
process.waitForFinished();
process.close();
Finally, if you just want to delete a file, you could use the QFile::remove function.
QFile file("f:\\b.txt");
if(file.remove())
qDebug() << "File removed successfully";
Author by
Mohammad Reza Ramezani
Updated on July 08, 2022Comments
-
Mohammad Reza Ramezani almost 2 years
I'm using CMD by
QProcess
but I have a problem.My code:
QProcess process; process.start("cmd.exe"); process.write ("del f:\\b.txt\n\r"); process.waitForFinished(); process.close();
When I don't pass an argument for
waitForFinished()
it waits for 30 secs. I want to terminateQProcess
after CMD command is executed! Not much and not less! -
epsilon almost 10 yearsJust for the sake of completion, as your anwser demonstrates several ways, I would add that passing -1 to QProcess::waitForFinished, would not trigger any timeout
-
Mohammad Reza Ramezani almost 10 yearsIt waits long And also did not work! It`s a sample code. I want to use CMD for other jobs not deleting
-
TheDarkKnight almost 10 yearsIf you're using command for other tasks, it would be easier (in my opinion) to create a script and call that from QProcess.
-
epsilon almost 10 years@MohammadRezaRamezani Same advice as Merlin069. Create a batch, run it as its answer show.
-
Mohammad Reza Ramezani almost 10 years@jbh All thing I need it in the first post. I wnat use mentioned code and wait to finish command prpmt completion not 30secs