限制程序多开数目
有限制只能运行一个程序实例的可以使用Event(事件)或者Mutex(互斥量)内核对象检查GetLastError,如果需要限制只能运行数个实例呢(>1,有些奇怪的需求)?
我们可以借助Semaphore(信号量)来完成,下面是基本代码:
class OnlyCountRunning{HANDLE handle;public: OnlyCountRunning(int count):handle(0) { const char *szName="xxx"; handle=CreateSemaphore(NULL,0,count,szName); if(handle&&GetLastError()==ERROR_ALREADY_EXISTS) { if(!ReleaseSemaphore(handle.1,NULL)) { CloseHandle(handle); exit(0);//only count running } } else { ReleaseSemaphore(handle.1,NULL) } } ~OnlyCountRunning(int count) { if(handle) { WaitForSingleObject(handle,INFINITE); CloseHandle(handle); } }};