www.pudn.com > loggerclient_src.zip > ClientPipeInstance.cpp


/* 
 *	$Header: /logger/loggertest/Pipe.cpp 1     11/11/03 2:44a Administrator $ 
 * 
 *	$History: Pipe.cpp $ 
 *  
 * *****************  Version 1  ***************** 
 * User: Administrator Date: 11/11/03   Time: 2:44a 
 * Created in $/logger/loggertest 
 */ 
#include "stdafx.h" 
#include "ClientPipeInstance.h" 
#include "..\common\Sleeper.h" 
#include "..\common\SecurityToken.h" 
 
#ifdef _DEBUG 
#undef THIS_FILE 
static char THIS_FILE[]=__FILE__; 
#define new DEBUG_NEW 
#endif 
 
////////////////////////////////////////////////////////////////////// 
// Construction/Destruction 
////////////////////////////////////////////////////////////////////// 
CClientPipeInstance::CClientPipeInstance() 
{ 
	m_hPipe = HANDLE(NULL); 
} 
 
CClientPipeInstance::~CClientPipeInstance() 
{ 
	Close(); 
} 
 
void CClientPipeInstance::Initialise(LPCTSTR szPipename) 
{ 
	ASSERT(szPipename); 
	ASSERT(AfxIsValidString(szPipename)); 
 
	m_csPipename = szPipename; 
	m_hPipe = HANDLE(NULL); 
} 
 
void CClientPipeInstance::Close() 
{ 
	if (m_hPipe != HANDLE(NULL)) 
	{ 
		DisconnectNamedPipe(m_hPipe); 
		CloseHandle(m_hPipe); 
	} 
 
	m_hPipe = HANDLE(NULL); 
} 
 
BOOL CClientPipeInstance::Write(LPCTSTR szData) 
{ 
	ASSERT(szData); 
	ASSERT(AfxIsValidString(szData)); 
 
	DWORD		   dwDataLen, 
				   dwError; 
	CSleeper	   ss; 
	CSecurityToken sa; 
 
	if (m_csPipename.IsEmpty()) 
		return FALSE; 
	 
	try 
	{ 
		if (m_hPipe == HANDLE(NULL)) 
		{ 
			if (WaitNamedPipe(m_csPipename, PIPE_WAIT_TIME)) 
			{ 
				while (TRUE) 
				{ 
					if ((m_hPipe = CreateFile(m_csPipename, GENERIC_WRITE, 0, &sa, OPEN_EXISTING, 0, NULL)) != INVALID_HANDLE_VALUE) 
						return WriteFile(m_hPipe, szData, _tcslen(szData), &dwDataLen, NULL); 
					else if (GetLastError() == ERROR_PIPE_BUSY) 
					{ 
						ss.Sleep(50); 
						continue; 
					} 
					else 
						return FALSE; 
				} 
			} 
 
			return FALSE; 
		} 
		else if (WriteFile(m_hPipe, szData, _tcslen(szData), &dwDataLen, NULL) == 0) 
		{ 
			dwError = GetLastError(); 
 
			if (dwError == ERROR_BROKEN_PIPE) 
			{ 
				//	Our pipe went away 
				CloseHandle(m_hPipe); 
				m_hPipe = HANDLE(NULL); 
				return FALSE; 
			} 
		} 
	} 
	catch(...) 
	{ 
		TRACE("Caught unknown exception in CClientPipeInstance::Send\n"); 
		return FALSE; 
	} 
 
	return TRUE; 
}