I am using a device driver that occasionaly misses an interrupt from hardware.
To read data from the device, I use the function
BOOL WINAPI ReadFile(
__in HANDLE hFile,
__out LPVOID lpBuffer,
__in DWORD nNumberOfBytesToRead,
__out_opt LPDWORD lpNumberOfBytesRead,
__inout_opt LPOVERLAPPED lpOverlapped
);
This function blocks forever when the device driver misses an interrupt. This results in the program stalling, and one has to restart windows to resolve it.
To fix this, I want to use a timeout-limit when calling Readfile(). But when I use
BOOL WINAPI SetCommTimeouts(
__in HANDLE hFile,
__in LPCOMMTIMEOUTS lpCommTimeouts
);
it fails with error code 87 (invalid parameters). Apparently, I can't use this timeout stuff on a device driver handle. How can I fix this? Is there some other way to set a timeout limit on a device driver?
thanks
You need to switch to asynchronous I/O. Open the device driver supplying the FILE_FLAG_OVERLAPPED flag to CreateFile and then pass an overlapped structure when you call ReadFile. The handle will be signaled when the i/o completes so you can use WaitForSingleObject where you supply the Handle passed to ReadFile and a timeout.
Not all device drivers support asynch I/O so this may not actually work for you. If this is the case, the ReadFile will still block and not return "ERROR_PENDING_IO".
If you timeout, you should also call CancelIO to kill the ReadFile before the overlapped structure goes out of scope. Otherwise, if it happens to finish later, it'll try to write the memory the overlapped structure used to live in.
Asynch i/o is a bit tricky to get right so read the docs carefully.
Update: An alternative occurred to me that you can call CancelIEx from a watchdog thread. Being a newer API, it may not be present on the platforms you have to support.