使用GetOverlappedResult丢失数据?

时间:2012-11-28 15:50:18

标签: c++ winapi io serial-port

我有一个不断寻找新数据的线程,如果数据不在串行缓冲区中,ReadFileGetOverlappedResult似乎告诉我有数据,并且它会读取它,但是不要把它转移到我的缓冲区......

func read()
{
    if(state == 0)
    {
        memset(bytes, '\0', sizeof(amount_to_read));

        readreturn = ReadFile(h, bytes, amount_to_read,NULL, osReader);
        if(readreturn <= 0)
        {
            errorcode = GetLastError();
            if(errorcode != ERROR_IO_PENDING)
            {
                SetEAIError(ERROR_INTERNALERROR);
                return -1;
            }
        }
    }

    if (GetOverlappedResult(h, osReader, &dwRead, FALSE) == false)
    {
        errorcode = GetLastError();

        if (errorcode == ERROR_IO_INCOMPLETE || errorcode == 0)
        {
            if(dwRead > 0)
            {
                return 1;
            }
            //timeout
            SetEAIError(ERROR_EAITIMEOUT);
            return -1;
        }
        else
        {
            //other error 
            SetEAIError(ERROR_WIN_ERROR);
            return -1;
        }
    }
    else
    {
        //read succeded, check if we read the amount required
        if(dwRead != amount_to_read)
        {
            if(dwRead == 0)
            {
                //nothing read, treat as timeout
                SetEAIError(ERROR_EAINOREAD);
                return -1;
            }
            else
            {
                //memcpy_s(bytes, sizeof(bytes), readbuf, dwRead);
                SetEAIError(ERROR_PARTIALREAD);
                *_bytesRead = dwRead;
                return -1;
            }
        }
        else
        {
            if(strlen((char*)bytes) == 0)
            {
                //nothing read, treat as timeout
                SetEAIError(ERROR_EAINOREAD);
                return -1;
            }
            //memcpy_s(bytes, sizeof(bytes), readbuf, dwRead);
            *_bytesRead = dwRead;
            return 0;
        }
    }
}

这是错误代码的含义:

  • ERROR_TIMEOUT - 将状态切换为1,使其不再读取,再次调用GetOverlappedResult

  • INTERNALERROR,ERROR_EAINOREAD - 它将状态重置为0

  • ERROR_PARTIALREAD - 以新的字节数开始新读取

如果我将GetOverlappedResult切换为阻塞(传递TRUE),它每次都有效。 如果我将我的线程切换为仅在我知道有数据时才会读取它每次都有效。

但如果那里没有数据,当有数据时,它似乎“丢失”数据,我的读取数量参数dwRead显示读取的正确字节数(可以看到它用端口读取)监视器)但字节不存储在我的char *。

我经常收到ERROR_EAINOREAD

我做错了什么?

我不想使用标志,我想只使用ReadFileGetOverlappedResult,我应该能够用我拥有的代码完成这个.......我假设< / p>

1 个答案:

答案 0 :(得分:3)

问题正是所说的数据丢失了......它丢失的原因是因为传入readfile的bytes参数是父线程中的局部变量。在本地,它会在每个循环中重新初始化,所以在我再次进入读取之后,跳过readfile并转到重叠的结果,我现在可能正在处理不同的内存区域

相关问题