您的位置:首页 > 其它

I/O 异步访问

2013-09-26 11:48 330 查看
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;

HANDLE g_readEvent, g_writeEvent;

int main()
{
g_readEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
g_writeEvent = CreateEvent( NULL, FALSE, FALSE, NULL );

HANDLE hFile1 = CreateFile( TEXT("1.TXT"),
GENERIC_READ | GENERIC_WRITE,
0, // must be opened with exclusive-access
NULL, // no security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
FILE_FLAG_OVERLAPPED, // overlapped I/O
NULL // htemplate must be NULL for comm devices
);

if( INVALID_HANDLE_VALUE == hFile1 )
{
cout << " open File failed !" << endl;
}
else
{
/* read process */
BYTE bBuffer[100] = { 0 };
OVERLAPPED o = { 0 };
o.Offset = 0;
o.hEvent = g_readEvent;

BOOL bReadDone = ReadFile( hFile1, bBuffer, 100, NULL, &o );

/* write process */
BYTE bWriteBuffer[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
OVERLAPPED oWrite = { 0 };
oWrite.Offset = 10;
oWrite.hEvent = g_writeEvent;

WriteFile( hFile1, bWriteBuffer, _countof( bWriteBuffer ), NULL, &oWrite );

HANDLE h[2];
h[0] = o.hEvent;
h[1] = oWrite.hEvent;

while(1)
{
DWORD dwStatus = WaitForMultipleObjects( 2, h, FALSE, INFINITE );
switch ( dwStatus - WAIT_OBJECT_0 )
{
case  0:
cout << " Read complete " << endl;
break;
case 1:
cout << " Write complete " << endl;
break;
default:
break;
}
}

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: