IOBYEVNT.C-----overlapped I/O with signaled everts

来源:互联网 发布:淘宝申请介入会退款吗 编辑:程序博客网 时间:2024/06/06 12:26

使用event对象搭配overlapped I/O,你就可以对同一个文件发出多个读取操作和多个写入操作,每一操作有自己的event对象;然后再调用WaitForMultipleObjects()来等待其中之一(或全部)完成。

以下函数能够将一个特定的请求(并指定文件偏移值和数据大小)记录起来等待执行。

#include<windows.h>

//need to keep the events in their own array so we can wait on them


HANDLE ghEvents[MAX_REQUESTS]; 
//keep track of each individual I/O operation
OVERLAPPED gOverlapped[MAX_REQUESTS];
//Handle to the file of interest.
HANDLE ghFile;
//Need a place to put all this data
char gBuffers[MAX_REQUESTS][READ_SIZE];
int QueueRequest(int nIndex, DWORD dwLocation, DWORD dwAmount)
{
int i;
BOOL rc;
DWORD dwNumread;
DWORD err;
MTVRIFY(ghEvents[nIndex] = CreateEvent(NULL, TRUE, FALSE, NULL));
gOverlapped[nIndex].hEvent = ghEvents[nIndex];
gOverlapped[nIndex].Offset = dwLocation;
for (i = 0; i < MAX_TRY_COUNT; i++)
{
rc = ReadFile(ghFile, gBuffers[nIndex], dwAmount,
&dwNumread, &gOverlapped[nIndex]);


  //Handle success
  if (rc)
  {
 printf("Read #%d complete immediately.\n", nIndex);
 return TRUE;
  }
  err = GetLastError();
  //Handle the error that isn't an error.rc is zero here.
  if (err == ERROR_IO_PENDING)
  {
//asynchronous i/o is still in progress
 printf("Read #%d queued for overlapped I/O.\n", nIndex);
 return TRUE;
  }
   //Handle recoverable error
  if (err == ERROR_INVALID_USER_BUFFER || err == ERROR_NOT_ENOUGH_QUOTA || err == 
  ERROR_NOT_ENOUGH_MEMORY)
  {
  Sleep(50);//wait around and try later
  continue;
  }
    //Give up on fatal error;
    break;
   }
    printf("ReadFile failed .\n");
    return -1;

}


这段代码为每一个“overlapped I/O请求”产生一个新的event对象,其handle 存放在OVERLAPPED结构之中,也存放在一个全局数组中,以便给WaitForMultipleObjects()使用。


0 0
原创粉丝点击