commit 3323a8bdb529e48615fcbac83e0d2bdaca039e9e Author: kiritow <1362050620@qq.com> Date: Thu Nov 16 21:47:54 2017 +0800 Initial Commit diff --git a/WinUtil.cpp b/WinUtil.cpp new file mode 100644 index 0000000..5cdf9ed --- /dev/null +++ b/WinUtil.cpp @@ -0,0 +1,88 @@ +#include "WinUtil.h" +using namespace std; + +SharedMemory::SharedMemory(const string& name) +{ + hMap=OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,name.c_str()); + if(hMap!=NULL) pMem=MapViewOfFile(hMap,FILE_MAP_ALL_ACCESS,0,0,0); + else pMem=nullptr; +} + +SharedMemory::SharedMemory(const string& name,int size) +{ + hMap=CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,size,name.c_str()); + if(hMap!=NULL) pMem=MapViewOfFile(hMap,FILE_MAP_ALL_ACCESS,0,0,0); + else pMem=nullptr; +} + +SharedMemory::~SharedMemory() +{ + if(pMem) + { + UnmapViewOfFile(pMem); + } + if(hMap!=NULL) + { + CloseHandle(hMap); + } +} + +bool SharedMemory::isReady() const +{ + return (hMap!=NULL); +} + +void* SharedMemory::get() +{ + return pMem; +} + + +NamedMutex::NamedMutex(const string& name, bool create) +{ + if(create) + { + hmtx=CreateMutex(NULL,TRUE,name.c_str()); + } + else + { + hmtx=OpenMutex(MUTEX_ALL_ACCESS,FALSE,name.c_str()); + } + if(hmtx==NULL) + { + errcode=GetLastError(); + } +} + +NamedMutex::~NamedMutex() +{ + if(hmtx!=NULL) + { + CloseHandle(hmtx); + } +} + +bool NamedMutex::isReady() const +{ + return (hmtx!=NULL); +} + +DWORD NamedMutex::getError() const +{ + return errcode; +} + +void NamedMutex::wait() +{ + WaitForSingleObject(hmtx,INFINITE); +} + +void NamedMutex::wait_for(int ms) +{ + WaitForSingleObject(hmtx,ms); +} + +void NamedMutex::release() +{ + ReleaseMutex(hmtx); +} diff --git a/WinUtil.h b/WinUtil.h new file mode 100644 index 0000000..60c5949 --- /dev/null +++ b/WinUtil.h @@ -0,0 +1,38 @@ +#include +#include + +class SharedMemory +{ +public: + /// Open a shared memory + SharedMemory(const std::string& name); + /// Create a shared memory + SharedMemory(const std::string& name,int size); + /// auto close, destroy memory. + ~SharedMemory(); + + bool isReady() const; + void* get(); + +private: + HANDLE hMap; + void* pMem; +}; + +class NamedMutex +{ +public: + NamedMutex(const std::string& name,bool create=false); + ~NamedMutex(); + + bool isReady() const; + DWORD getError() const; + + /// If the mutex has been occupied by this process, wait() will return immediately. + void wait(); + void wait_for(int ms); + void release(); +private: + HANDLE hmtx; + DWORD errcode; +};