內核對象是所有Windows進程都可以訪問的,因此可以使用其中的互斥信號量和事件對象使程序單實例運行。。
比起原來的IO鎖好了很多 = = DEMO如下:
【使用互斥信號量(互斥對象)實現】
- //////////////////////////////////////////////////////////////////////////
- // CopyRight(c) 2009, YOYO, All Rights Reserved.
- // Author: LIN YiQian
- // Created: 2009/09/16
- // Describe: 使用內核對象控制程序只能單實例 演示
- //////////////////////////////////////////////////////////////////////////
- #include <Windows.h>
- #include <iostream>
- using namespace std;
- void main(void)
- {
- HANDLE hInstance = CreateMutex(NULL, TRUE, "SingleInstance");
- if (hInstance)
- {
- if (ERROR_ALREADY_EXISTS == GetLastError())
- {
- printf("程序已經啓動!");
- system("pause");
- return;
- }
- }
- while (true)
- {
- printf("程序運行阿 = = 運行阿 = = 運行阿。。/n");
- Sleep(100);
- }
- CloseHandle(hInstance);
- return;
- }