1

当调用 GetOverlappedResult 时,以下代码永远挂起,我在 windows 异步 IO 操作方面没有太多经验,我根据自己的理解实现了它。我用它来访问虚拟网络接口(通过 openvpn - TAP/TUN 接口,其内核驱动程序安装正确)。

我找到了它挂起的地方,但我不知道它挂起的原因?

nread = 0;
memset(data_buffer, '\0', nread);
OVERLAPPED overlapped_read;
memset(&overlapped_read, 0, sizeof(overlapped_read));
overlapped_read.Offset = 0;
overlapped_read.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

if ( ReadFile(fd, data_buffer, len, &nread, &overlapped_read) == false ) {
    if (GetLastError() != ERROR_IO_PENDING) {
        std::cerr << "ReadFile failed : " << GetLastError() << std::endl;
        return false;
    }
    else {
        DWORD dwRes = WaitForSingleObject(overlapped_read.hEvent, INFINITE);
        if(dwRes == WAIT_OBJECT_0) {
            if (!GetOverlappedResult(fd, &overlapped_read, &nread, FALSE)) {
                std::cout << "GetOverlappedResult failed : ErrorCode = "
                          << GetLastError() << std::endl;
                CloseHandle(overlapped_read.hEvent);    
                return false;
            }
            else {
                std:cout << "Read successfull." << std::endl;
            }
        }    
        else {    
            std::cout << "WaitForSingleObject failed : ErrorCode = "
                      << GetLastError() << std::endl;
            CloseHandle(overlapped_read.hEvent);    
            return false;    
        }
    }
    std::cout << "bytes read = " << nread << std::endl;    
    CloseHandle(overlapped_read.hEvent);    
    return TRUE;
}

上面的代码在使用 CreateThread API 创建的线程内的无限 while 循环中执行。

我是否正确实现了异步操作?

GetOverlappedResult 挂起时可能出现哪些情况?

PS:很少有 ReadFile 调用成功,它可以成功读取以太网帧,但大约挂起。15-20 个电话。

4

0 回答 0