对ReadFile堵塞进行异步处理

此前使用ReadFile函数时,都是同步,这样会导致比如说一条管道,一端写入,另一端读取。若写入端出现问题或者写入不成功,读取端会一直堵塞在ReadFile处,程序就一直卡住。因此,考虑使用异步处理,通过一定时间超时判断,如果一直读不到数据就自动向下执行程序。

管道的创建读取端:


#include "stdafx.h"
#include 
#include 
#include 
#include 

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	char buf[100]{0};
	DWORD dwRead, dwLength;
	OVERLAPPED ov;
	ov.Offset = 0;
	ov.OffsetHigh = 0;
	ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	//设置FILE_FLAG_OVERLAPPED
	HANDLE hPipe = CreateNamedPipe("\\\\.\\pipe\\pipe1", PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0, 1, 1024, 1024, 0, NULL);

	//先延时一会让另一端打开连接管道
	Sleep(3000);

	DWORD tStart, tCurrent;
	tStart = GetTickCount() / 1000;

	//如果管道另一端写入成功的话,这边立马收到数据并向下执行
	if (!ReadFile(hPipe, buf, 100, &dwRead, &ov))
	{
		//如果管道另一端写入失败的话,这边收不到数据,经过超时后自动退出循环,并向下执行
		while (!GetOverlappedResult(hPipe, &ov, &dwLength, FALSE))
		{
			tCurrent = GetTickCount() / 1000;
			if ((tCurrent - tStart) > 8)
				break;

			Sleep(1000);
		}

	}

	cout << buf << endl;
	system("pause");
	return 0;
}


管道的连接写入端:


#include "stdafx.h"
#include 
#include 
#include 
#include 

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
		char buf[100]{0};
		DWORD dwWrite;


		WaitNamedPipe("\\\\.\\pipe\\pipe1", NMPWAIT_WAIT_FOREVER);
		HANDLE hPipe = CreateFile("\\\\.\\pipe\\pipe1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if (INVALID_HANDLE_VALUE == hPipe){
			cout << "invalid handle" << endl;
		}

		//写入成功的话,管道另一端立马收到数据并向下执行
		//写入失败的话,管道另一端收不到数据,经过超时后自动向下执行
		WriteFile(hPipe, "678gjhs", 8, &dwWrite, 0);

	
		system("pause");
		return 0;
}


你可能感兴趣的:(c++,多进程)