I am porting a Unix console program to Windows. And it uses posix threads
and piping.
It uses the POSIX 'select()' function to know whether there is data in a
pipe. But 'select()' on Windows only works on sockets.
I need to find whether a pipe has any data and if so read it, otherwise skip
to the next task.
I have looked at 'WaitForSingleObject()', it works with STDIN, but it does
not appear to work with standard file handles or pipes.
state = WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 20000);
Works for standard input.
Many thanks in advance,
Aaron
AFAIK, you must use ReadFile
(http://msdn.microsoft.com/en-us/library/aa365467%28v=vs.85%29.aspx)
with the optional OVERLAPPED
(http://msdn.microsoft.com/en-us/library/ms684342%28v=vs.85%29.aspx)
structure initialized properly (hEvent = CreateEvent(..))
If ReadFile() returns FALSE with GetLastError() == ERROR_IO_PENDING,
you'll have to wait on the hEvent member for data (that's the select
part) ; as a pending request is in progress (ie. do not trash the memory
region now of you're going to have troubles)
If the WaitForSingleObject returns successfully (WAIT_OBJECT_0),
GetOverlappedResult() can be used to get the number of bytes actually
read. Otherwise, CancelIo() to cancel the pending request.
Yes, this is painful. And experimentally it sometimes does not work
properly (pipe blocking, and so on..) so the best way is NOT to use
pipes at all on Windows, IMHO.
Okay I will look into this.
> If the WaitForSingleObject returns successfully (WAIT_OBJECT_0),
> GetOverlappedResult() can be used to get the number of bytes actually
> read. Otherwise, CancelIo() to cancel the pending request.
I cannot see how to get a handle from a pipe handle in order to do that.
There does not appear to be an equivalent to 'GetStdHandle()' for normal
file handles.
> Yes, this is painful. And experimentally it sometimes does not work
> properly (pipe blocking, and so on..) so the best way is NOT to use
> pipes at all on Windows, IMHO.
The app I am trying to port uses pThreads.
Thanks, yes this is painful your right !
Aaron
(HANDLE) _get_osfhandle(pipe[..]) ?
Brill, thanks Xavier,
Aaron