#include "stdafx.h"
#include<windows.h>
#include<stdio.h>
HANDLE hFile;
OVERLAPPED overlap={0};
char content[10]={0};
VOID CALLBACK wf(DWORD dwErrorCode,DWORD dwNumberOfBytes,LPOVERLAPPED lpO){
Sleep(2000);
printf("APC写文件结束\n");
}
VOID CALLBACK rf(DWORD dwErrorCode,DWORD dwNumberOfBytes,LPOVERLAPPED lpO){
printf("APC读取文件的内容:%s\n",content);
}
void* fun(void*){
printf("线程开始\n");
Sleep(2000);
char hw[]="haha.txt";
if(!WriteFileEx(hFile,(LPVOID)hw,sizeof(hw),&overlap,(LPOVERLAPPED_COMPLETION_ROUTINE)wf)){
printf("WriteFile failed:%d\n",GetLastError());
}
if(!FlushFileBuffers(hFile)){
printf("Flush failed\n");
}
printf("线程结束\n");
SleepEx(INFINITE, TRUE);//等待本线程注册的APC函数wf结束
printf("SleepEx等待写操作APC结束\n");
return NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
hFile=CreateFile("d:\\abc.txt",
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_WRITE|FILE_SHARE_READ,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,
NULL);
if(INVALID_HANDLE_VALUE==hFile){
printf("CreateFile 失败:%d\n",GetLastError());
return 1;
}
HANDLE hThread=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)fun,NULL,0,NULL);
if(NULL==hThread){
printf("CreateThread 失败:%d\n",GetLastError());
return 1;
}
printf("main等待\n");
WaitForSingleObject(hThread,INFINITE);//一定要等待Thread通知结束
printf("main Wait结束\n");
SetFilePointer(hFile, 0, 0, FILE_BEGIN);
ReadFileEx(hFile,(LPVOID)content,20,&overlap,(LPOVERLAPPED_COMPLETION_ROUTINE)rf);
SleepEx(INFINITE, TRUE);//等待本线程注册的APC函数rf结束
printf("main结束\n");
CloseHandle(hFile);
return 0;
}
|