C++ 管道

// PipeServer.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <process.h>
using namespace std;
#pragma warning(disable:4996)

HANDLE hClose = NULL;

unsigned int _stdcall ProcessPipe(void *lp)
{
	HANDLE hPipeServer = (HANDLE)lp;
	BYTE btRead[MAX_PATH] = {0};

	DWORD dwTime = GetTickCount();
	while (GetTickCount() - dwTime < 10000){
		DWORD dwRead = 0;
		BOOL bRet = ReadFile(hPipeServer, btRead, MAX_PATH, &dwRead, NULL);
		if (!bRet){
			if (GetLastError() == ERROR_BROKEN_PIPE ){
				break;
			}
		}
		else{
			printf("%s\n", btRead);
			ZeroMemory(btRead, MAX_PATH);
			strcpy((char*)btRead, "RecvInfo");
			DWORD dwWrite = 0;
			bRet = WriteFile(hPipeServer, btRead, strlen((char*)btRead), &dwWrite, NULL);
		}
		Sleep(20);
	}

	SetEvent(hClose);
	DWORD dwExitCode = 0;
	GetExitCodeThread(GetCurrentThread(), &dwExitCode);
	_endthreadex(dwExitCode);
	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE hPipeServer = CreateNamedPipe(L"\\\\.\\pipe\\pipeServer", 
		PIPE_ACCESS_DUPLEX, 
		PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 
		4096,
		4096,
		NMPWAIT_USE_DEFAULT_WAIT, 
		NULL
		);
	if (hPipeServer == INVALID_HANDLE_VALUE){
		printf("CreateNamedPipe failed with error %d", GetLastError());
		return 0;
	}

	BOOL bRet = ConnectNamedPipe(hPipeServer, NULL);
	if (!bRet){
		printf("ConnectNamedPipe failed with error %d", GetLastError());
		return 0;
	}

	hClose = CreateEvent(NULL, true, false, NULL);
	HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, ProcessPipe, (LPVOID)hPipeServer, 0, NULL);
	CloseHandle(hThread);

	WaitForSingleObject(hClose, INFINITE);
	CloseHandle(hPipeServer);

	return 0;
}

.cpp

// PipeClient.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>
#include <process.h>
using namespace std;
#pragma warning(disable:4996)

int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE hPipe = CreateFile( 
		L"\\\\.\\pipe\\pipeServer",   // pipe name 
		GENERIC_READ | GENERIC_WRITE, 
		0,              // no sharing 
		NULL,           // default security attributes
		OPEN_EXISTING,  // opens existing pipe 
		0,              // default attributes 
		NULL);   

	char strInfo[MAX_PATH] = {0};
	strcpy(strInfo, "12sdfgsgdfg");
	DWORD dwWrite = 0;
	WriteFile(hPipe, strInfo, strlen(strInfo), &dwWrite, NULL);
	Sleep(500);
	ZeroMemory(strInfo, MAX_PATH);
	DWORD dwRead = 0;
	ReadFile(hPipe, strInfo, MAX_PATH, &dwRead, NULL);
	printf("%s\n", strInfo);
	Sleep(8000);
	CloseHandle(hPipe);
	return 0;
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

 

posted @ 2015-08-06 21:01  QQ76211822  阅读(412)  评论(0编辑  收藏  举报