Win32 串口编程(四)
来源:互联网 发布:陕西大数据公司好不好 编辑:程序博客网 时间:2024/06/06 13:21
7 通信超时
通信超时是影响读写操作的另一个重要方面。如果操作所用时间大于超时值,则操作完成,ReadFile、WriteFile、GetOverlappedResule或者WaitForSingleObject不会返回错误代码,它们都指示操作成功完成。实际传输的字节数小于请求的字节数是操作超时的唯一指示。如果ReadFile返回TRUE,但是读取到的字节数小于请求的字节数,则操作超时了。如果重叠写操作超时,则重叠事件句柄受信,WaitForSingleObject返回WAIT_OBJECT_0;GetOverlappedResult返回TRUE,dwBytesTransferred指示超时前已经传输的字节数。下面的代码展示了如何处理这种情况:
BOOL WriteABuffer(char * lpBuf, DWORD dwToWrite){ OVERLAPPED osWrite = {0}; DWORD dwWritten; DWORD dwRes; BOOL fRes;
// Create this write operation's OVERLAPPED structure hEvent. osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (osWrite.hEvent == NULL) // Error creating overlapped event handle. return FALSE;
// Issue write if (!WriteFile(hComm, lpBuf, dwToWrite, &dwWritten, &osWrite)) { if (GetLastError() != ERROR_IO_PENDING) { // WriteFile failed, but it isn't delayed. Report error. fRes = FALSE; } else // Write is pending. dwRes = WaitForSingleObject(osWrite.hEvent, INFINITE); switch(dwRes) { // Overlapped event has been signaled. case WAIT_OBJECT_0: if (!GetOverlappedResult(hComm, &osWrite, &dwWritten, FALSE)) fRes = FALSE; else { if (dwWritten != dwToWrite) { // The write operation timed out. I now need to // decide if I want to abort or retry. If I retry, // I need to send only the bytes that weren't sent. // If I want to abort, I would just set fRes to