1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| #include "stdafx.h" #include "Share.h"
CShare::CShare() { m_hFileMap = NULL; m_pSharedMem = NULL;
m_sharedLock = NULL; m_bhasLock = FALSE; }
CShare::~CShare() { UnLockMem(); DestroyShareMem(); }
BOOL CShare::InitShareMem() { m_sharedLock = OpenMutex(NULL, false, TEXT("SMTLCDM_Mutex")); if (m_sharedLock == NULL) { m_sharedLock = CreateMutex(NULL, FALSE, TEXT("SMTLCDM_Mutex")); if (!m_sharedLock) { return false; } }
void* buff = NULL;
if (NULL == m_hFileMap) { m_hFileMap = CreateFileMapping( (HANDLE)INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, SHARED_MEM_SIZE, SHARED_MEM_NAME );
buff = MapViewOfFile( m_hFileMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0 ); } else { buff = MapViewOfFile( m_hFileMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0 ); }
if (buff == (void*)-1) { ::UnmapViewOfFile(buff); ::CloseHandle(m_hFileMap); m_hFileMap = NULL; return FALSE; }
m_pSharedMem = (char*)buff; return TRUE; }
BOOL CShare::DestroyShareMem() { if (m_pSharedMem) { ::UnmapViewOfFile(m_pSharedMem); m_pSharedMem = nullptr; } if (m_hFileMap != nullptr) { m_hFileMap = nullptr; } return TRUE; }
BOOL CShare::LockMem() { if (m_sharedLock) { DWORD timeout = 1; DWORD waitres; waitres = WaitForSingleObject(m_sharedLock, timeout); if (waitres == WAIT_OBJECT_0) { m_bhasLock = TRUE; return TRUE; } if (waitres == WAIT_TIMEOUT) { m_bhasLock = FALSE; return FALSE; } return TRUE; }
m_bhasLock = FALSE; return FALSE; }
BOOL CShare::UnLockMem() { if (m_sharedLock) { ReleaseMutex(m_sharedLock); m_bhasLock = FALSE; }
return TRUE; }
void CShare::WriteData(const char* buff, int len) { memcpy(m_pSharedMem, buff, len); }
|