Reputation: 2066
I am using NamedPipes to communicate between different modules of our windows application. At one point it is possible that a read operation could take long time so we would like to add a timeout. I added the OVERLAPPED-flag like this:
pipeHandle = CreateFile(
pipename,
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
0,
nullptr,
OPEN_EXISTING,
0,
nullptr);
Then the read operation looks like this:
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
overlapped.hEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);
successful = ReadFile(
pipeHandle,
buffer,
4096 * sizeof(wchar_t),
&numBytesRead,
&overlapped
);
if (successful == FALSE)
{
LOG("Reading was not successful");
if (GetLastError() != ERROR_IO_PENDING)
{
// The function call failed. ToDo: recovery.
LOG_LAST_ERROR("Failed because of Error: ");
return ERROR_READ_FAULT;
}
else
{
// TODO: add a timeout...
successful = GetOverlappedResult(pipeHandle, &overlapped, &numBytesRead, TRUE);
}
}
else
{
LOG("Reading was successful");
// I/O completed:
return ERROR_SUCCESS;
}
Now I would expect that call to ReadFile would return immediatley so I could handle possible timeouts, but instead it blocks till the call returns.
What am I doing wrong?
Upvotes: 0
Views: 622
Reputation: 6303
In your code, the FILE_FLAG_OVERLAPPED
is in the dwDesiredAccess
parameter, but it should be specified in the dwFlagsAndAttributes
parameter.
So, this might work better:
pipeHandle = CreateFile(
pipename,
PIPE_ACCESS_DUPLEX,
0,
nullptr,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
nullptr);
Upvotes: 1