Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

win32: how stop ReadFile (stdin|pipe)

Tags:

c++

winapi

I have handle that I got via stdinHandle = GetStdHandle(STD_INPUT_HANDLE) and I have separate thread which execute such code:

while (!timeToExit) {
  char ch;
  DWORD readBytes = 0;
  if (!::ReadFile(stdinHandle, &ch, sizeof(ch), &readBytes, nullptr)) {
    //report error
    return;
  }
  if (readBytes == 0)
      break;
  //handle new byte
}

where timeToExit is std::atomic<bool>.

I wan to stop this thread from another thread. I tried this:

timeToExit = true;
CloseHandle(stdinHandle);

and code hangs in CloseHandle.

The code hangs while program is running by other program that uses CreatePipe and DuplicateHandle to redirect input of my program to pipe.

So how should I stop while (!timeToExit).. thread in win32 way? Or may be I should some how change while (!timeToExit).. thread to make it possible to stop it?

Update I thought about usage of WaitForMultipleObjects before call of ReadFile with stdin and event as arguments, and trigger event in other thread, but there is no mention of anonymous pipe as possible input for WaitForMultipleObjects, plus I tried when stdin connected to console, and it become useless (always return control without delay) after the first character typed into console, looks like I have to use ReadConsoleInput in this case, instead of ReadFile?

like image 885
fghj Avatar asked Dec 04 '25 13:12

fghj


1 Answers

When reading from a console's actual STDIN, you can use PeekConsoleInput() and ReadConsoleInfo() instead of ReadFile().

When reading from an (un)named pipe, use PeekNamedPipe() before calling ReadFile().

This will allow you to poll STDIN for new input before actually reading it, and then you can check your thread termination status in between polls.

You can use GetFileType() to detect what kind of device is attached to your STD_INPUT_HANDLE handle.

like image 116
Remy Lebeau Avatar answered Dec 07 '25 14:12

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!