104 lines
1.7 KiB
C++
104 lines
1.7 KiB
C++
#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;
|
|
}
|
|
|
|
int NamedMutex::wait()
|
|
{
|
|
return wait_for(INFINITE);
|
|
}
|
|
|
|
int NamedMutex::wait_for(int ms)
|
|
{
|
|
DWORD ret=WaitForSingleObject(hmtx,ms);
|
|
if(ret==WAIT_OBJECT_0)
|
|
{
|
|
return 1;
|
|
}
|
|
else if(ret==WAIT_TIMEOUT)
|
|
{
|
|
return 0;
|
|
}
|
|
else
|
|
{
|
|
// WAIT_ABANDONED
|
|
// WAIT_FAILED
|
|
errcode=GetLastError();
|
|
return -1;
|
|
}
|
|
}
|
|
|
|
void NamedMutex::release()
|
|
{
|
|
ReleaseMutex(hmtx);
|
|
}
|