In windows, how to have a non-blocking stdin that is a redirected pipe?

I have a Windows C program that gets its data through the stdin redirected channel, sort of like:

 ./some-data-generator | ./myprogram 

The problem is that I need to be able to read from stdin non-blocking way. The reason for this is that (1) the input is a data stream, and there is no EOF and (2) the program must be able to interrupt the stdin -reading stream at any time. fread blocks when there is no data, so it is very difficult.

On Unix, this is not a problem, since you can set the fcntl and O_NONBLOCK file descriptor lock mode. However, fcntl does not exist in windows.

I tried using SetNamedPipeHandleState :

  DWORD mode= PIPE_READMODE_BYTE|PIPE_NOWAIT; BOOL ok= SetNamedPipeHandleState(GetStdHandle(STD_INPUT_HANDLE), &mode, NULL, NULL); DWORD err= GetLastError(); 

but this is not with ERROR_ACCESS_DENIED ( 0x5 ).

I'm not sure what else to do. Is it really impossible (!) Or just really confused? Online resources are quite rare for this particular problem.

+6
c ++ c windows pipe stdin
source share
2 answers

Order evaluation, check if there is an input ready for reading:

  • In console mode, you can use GetNumberOfConsoleInputEvents ().
  • You can use PeekNamedPipe () to redirect channels
+3
source share

You can use async-I / O to read from a descriptor, for example, calling ReadFileEx () WIN32. Use CancelIo () to stop reading when there is no input.

See MSDN at http://msdn.microsoft.com/en-us/library/aa365468(VS.85).aspx

+1
source share

All Articles