Is it possible to wait on ReadFile ()?

while(GetExitCodeProcess(processInfo.hProcess, &exitCode)
        && exitCode == STILL_ACTIVE)
{
    ReadFile(defaultSTDIN, chBuf, 1, &dwRead, 0);
    WriteFile(writingEnd, chBuf, 1, &dwWritten, 0);
}

The problem with the above code is that even when the child process referenced by processInfo.hProcess has logged out, we are still stuck in the while loop because ReadFile () is waiting for input. What is the best way to solve this problem?

+3
source share
2 answers

You need to read the asynchronous file using the flag FILE_FLAG_OVERLAPPEDwhen opening the file and specifying the structure of the OVERLAPPEDfunction ReadFile. Then you can wait for both the read operation and the completion of the process and act accordingly.

+7
source

We can assume a timeout with an non-overlapping ReadFile, but indirectly.

, SetCommTimeouts, , , ReadTotalTimeoutConstant . ( : , , , , , .)

ReadFile , , . - - , , -, dwRead . 1 , if dwRead = 0, -, .

, ( , - ) :

    COMMTIMEOUTS timeouts = { 0, //interval timeout. 0 = not used
                              0, // read multiplier
                             10, // read constant (milliseconds)
                              0, // Write multiplier
                              0  // Write Constant
                            };


    SetCommTimeouts(defaultSTDIN, &timeouts);

    while(GetExitCodeProcess(processInfo.hProcess, &exitCode)
          && exitCode == STILL_ACTIVE)
    {
        ReadFile(defaultSTDIN, chBuf, 1, &dwRead, 0);
        if (dwRead == 0) {
                     //insert code to handle timeout here
        }
        WriteFile(writingEnd, chBuf, 1, &dwWritten, 0);
    }
+5

Source: https://habr.com/ru/post/1772350/


All Articles