1

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?

4

1 回答 1

3

我不确定检查子进程是否正在等待用户输入是否有意义——首先,因为我不相信有任何现实的方法可以做到这一点,其次,因为没有必要——任何数据write()如果/当它尝试从标准输入读取时,QProcess 将被子进程缓冲和读取。(根据定义,子进程将相对于您自己的进程异步执行,因此任何依赖于知道子进程“当前正在做什么”的方法本质上都是可疑的,因为子进程当前正在执行的操作可以并且将会在没有通知的情况下更改下一瞬间,在您的流程有时间做出反应之前)

可以做的(如果您愿意)是读取子进程的 stdout 和/或 stderr 流,并对子进程的输出做出反应。(例如,如果您知道子进程将在某些时候打印enter your decision now ->到标准输出,您可以从 QProcess 的 StandardOutput 通道读取标准输出数据,并在看到该字符串时做出适当的反应)

于 2018-10-31T02:41:50.587 回答