问题描述
当您对使用 CreateFile()
或 _get_osfhandle()
创建的句柄调用 WaitForSingleObject()
时会发生什么?>
出于不值得解释的原因,我想使用 WaitForSingleObject()
来等待我用 _get_osfhandle(fd)
创建的 HANDLE,其中 fd
来自对 _open()
的常规调用.这可能吗?
我已经在实践中尝试过,在某些机器上它按预期工作(HANDLE 始终处于信号状态,因为您可以从中读取更多数据),并且在某些机器上 WaitForSingleObject()
如果你让它无限期地阻止.
WaitForSingleObject()
的 MSDN 页面说它处理的唯一支持的事情是更改通知、控制台输入、事件、内存资源通知、互斥锁、进程、信号量、线程和可等待计时器."
另外,如果我在 CRT 文件描述符上使用 CreateFile()
而不是 _get_osfhandle()
会有所不同吗?
不要这样做.如您所见,它具有未定义的行为.
即使定义了行为,它的定义方式也相对没有用,除非您不喜欢编写额外的代码.当该句柄上的任何异步 I/O 操作完成时会发出信号,这不能概括为跟踪哪个 I/O 操作完成.
为什么要等待文件句柄?显然,当您正在做的事情甚至没有得到足够的支持而不会无限期地阻止时,意图很重要.
What happens when you call WaitForSingleObject()
on a handle you've created with CreateFile()
or _get_osfhandle()
?
For reasons not worth explaining I would like to use WaitForSingleObject()
to wait on a HANDLE that I've created with _get_osfhandle(fd)
, where fd
comes from a regular call to _open()
. Is this possible?
I have tried it in practice, and on some machines it works as expected (the HANDLE is always in the signaled state because you can read more data from it), and on some machines WaitForSingleObject()
will block indefinitely if you let it.
The MSDN page for WaitForSingleObject()
says that the only supported things that it handles are "change notifications, console input, events, memory resource notifications, mutex, processes, semaphores, threads, and waitable timers."
Additionally, would it be different if I used CreateFile()
instead of _get_osfhandle()
on a CRT file descriptor?
Don't do it. As you can see, it has undefined behavior.
Even when the behavior is defined, it's defined in such a way as to be relatively not useful unless you don't like writing additional code. It is signaled when any asynchronous I/O operation on that handle completes, which does not generalize to tracking which I/O operation finished.
Why are you trying to wait on a file handle? Clearly the intent matters when you are doing something that isn't even supported well enough to not block indefinitely.
这篇关于WaitForSingleObject 在文件句柄上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!