Aleksandar
Aleksandar

Reputation: 77

Determine if QProcess is waiting for user input

I am working on an application (developed in Qt 5.11, toolchain MSVS2017 64bit) which will, at some point, have to execute a .bat script. This .bat script will call certain program with appropriate cmd line arguments. Script and program will reside in same directory. This program may or may not require user to press Enter at the end. If program requires user to press Enter, program would never finish unless new line character is written in stdin.

I want to check if program is waiting for user input before trying to write to its stdin, if possible using only Qt library.

The .bat script would simply call program:

Program arg1 arg2 arg3...

From application, script would execute using QProcess:
Added spleep after start of process

QProcess process;
process.setWorkingDirectory("C:/path/to/script");
process.start("cmd /C C:/path/to/script/script.bat");

QThread::sleep(someTimeout);  // give enough time for process to finish

if (/*somehow*/ process.isWaitingForInput())
    proces.write("\n");
process.waitForFinished();
process.readAllStandardOutput();
process.readAllStandardInput();
proces.exitCode();

I have found similar question with answer pointing to MSDN WaitForInputIdle.

In future port to Linux or Mac is possible and if it is possible I would like to avoid

#if defined(WIN32)
    WaitForInputIdle(...)
#else
    PosixAlternative(...)
#endif

Also, maybe of topic, but I am curious, is it possible to to execute .bat script from QProcess in a way that cmd/terminal window is shown along with std output?

Upvotes: 1

Views: 934

Answers (1)

Jeremy Friesner
Jeremy Friesner

Reputation: 73051

I'm not sure it makes sense to check if the child process is waiting for user input -- first, because I don't believe there is any realistic way to do that, and second, because it's not necessary -- any data you write() to the QProcess will be buffered and read by the child process if/when it does try to read from stdin. (The child process will by definition be executing asynchronously relative to your own process, so any approach that relies on knowing what the child "is currently doing" is inherently suspect, since what the child process is currently doing can and will change without notice from one instant to the next, before your process has time to react)

What you can do (if you want to) is read the child process's stdout and/or stderr streams, and react to the child process's output. (e.g. if you know the child process will at some point print enter your decision now -> to stdout, you could read in the stdout-data from the QProcess's StandardOutput channel and react appropriately when you see that string)

Upvotes: 3

Related Questions