CreateMutex
The CreateMutex function creates or opens a named or unnamed mutex object.
HANDLE CreateMutex( LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCTSTR lpName); 在調用這個函數的時候,程序會以lpMutexAttributes和bInitialiOwner參數在當前的程序上下文中創建一個lpName指示的名字的Mutex,如果創建成功,程序返回新創建的mutex對象的handle,如果創建失敗,返回NULL,用戶可以調用GetLastError函數獲取錯誤代碼。如果lpName指示的這個mutex對象已經存在(程序已經存在運行實例),則函數返回已經存在的該mutex對象的句柄,調用GetLastError會得到ERROR_ALREADY_EXISTS的錯誤。
那么我們程序要做的就是創建這個mutex對象,檢測錯誤代碼,若是ERROR_ALREADY_EXISTS,則表明程序已經運行。
這是代碼:
CreateMutex(NULL,TRUE,"TestMutex"); DWORD lastError=GetLastError(); if(ERROR_ALREADY_EXISTS==lastError) { MessageBox(NULL,"An instance of thie program already exists!","Information",MB_OK); return 1; }
posted on 2009-05-17 16:45 悟山 閱讀(654) 評論(2) 編輯 收藏 引用
我怎么記得Mutex是不能跨進程的,Semaphore才可以。 回復 更多評論
Windows下可以,只用于線程的叫critical_section 回復 更多評論
Powered by: C++博客 Copyright © 悟山