win32:如何停止 ReadFile (stdin|pipe) [英] win32: how stop ReadFile (stdin|pipe)

查看:34
本文介绍了win32:如何停止 ReadFile (stdin|pipe)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有通过 stdinHandle = GetStdHandle(STD_INPUT_HANDLE) 获得的句柄,并且我有单独的线程来执行此类代码:

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
}

其中 timeToExitstd::atomic.

我想从另一个线程停止这个线程.我试过这个:

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

timeToExit = true;
CloseHandle(stdinHandle);

并且代码挂在 CloseHandle 中.

当程序被其他使用的程序运行时代码挂起CreatePipeDuplicateHandle 将我的程序输入重定向到管道.

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

那么我应该如何以 win32 方式停止 while (!timeToExit).. 线程?或者我应该如何更改 while (!timeToExit).. 线程以使其成为可能阻止它?

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?

更新在调用 ReadFile 之前,我考虑过使用 WaitForMultipleObjects标准输入和事件作为参数,并在其他线程中触发事件,但是没有提到匿名管道作为 WaitForMultipleObjects 的可能输入,而且我在 stdin 连接到控制台时尝试过,在输入控制台的第一个字符后,它变得无用(总是立即返回控制权),看起来我在这种情况下必须使用 ReadConsoleInput 而不是 ReadFile?

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?

推荐答案

从控制台的实际 STDIN 读取时,您可以使用 PeekConsoleInput()ReadConsoleInfo() 而不是 ReadFile().

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

从(未)命名管道读取时,使用PeekNamedPipe() 在调用 ReadFile() 之前.

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

这将允许您在实际读取新输入之前轮询 STDIN,然后您可以在轮询之间检查线程终止状态.

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.

您可以使用 GetFileType() 检测连接到您的 STD_INPUT_HANDLE 句柄的设备类型.

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

这篇关于win32:如何停止 ReadFile (stdin|pipe)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆