这是我的设计;
1)初始化AIO控制块;
memset(&m_ReadBuffer, 0, sizeof(struct aiocb));
m_ReadBuffer.aio_fildes = dup(m_Socket);
m_ReadBuffer.aio_buf = NULL; /* Not yet */
m_ReadBuffer.aio_nbytes = 0;
m_ReadBuffer.aio_offset = 0;
m_ReadBuffer.aio_reqprio = 0;
m_ReadBuffer.aio_lio_opcode = LIO_READ;
m_ReadBuffer.aio_sigevent.sigev_notify = SIGEV_THREAD;
m_ReadBuffer.aio_sigevent.sigev_value.sival_ptr = (void *) this;
m_ReadBuffer.aio_sigevent.sigev_notify_function = OnReadFinished;
m_ReadBuffer.aio_sigevent.sigev_notify_attributes = NULL;
2)然后触发异步读取操作;
int RetVal = aio_read(&m_ReadBuffer);
if (RetVal != 0)
return false;
return true;
3)这是我的完成程序;
static void OnReadFinished(sigval_t pArg)
{
ClassX *pTransport = (ClassX *) pArg.sival_ptr;
// aio_error returns 0 if the request completed successfully
int dwError = aio_error(&pTransport->m_ReadBuffer);
int32_t cbTransferred = 0;
// Did the request completed successfully
if (dwError == 0) {
// Cool, request completed, get the final retrun value.
cbTransferred = aio_return(&pTransport->m_ReadBuffer);
}
else {
// the request NOT completed, resheduling the reading process..
// ***HERE: I'm getting "Resource unavailable temporarily***
if (false == aio_read(&m_ReadBuffer))
return;
}
// ... some codes ..
return;
}
4)在AIO完成例程中,我在空闲时间内重复“资源暂时不可用”,但是当另一方发送内容时,我可以读取正确的数据。我认为Linux内核存在一个错误。如果套接字中没有数据,则不应使用“资源暂时不可用”错误调用AIO完成例程。它浪费了不必要的时间..
提前致谢