Making a singleton application across all users

こ雲淡風輕ζ 提交于 2019-12-02 03:28:30

问题


I'm trying to create an application which only allows a single instance across all Windows users.

I'm currently doing it by opening a file to write and leaving it open. Is this method safe? Do you know of an alternative method using C?


回答1:


The standard solution is to create a global mutex during application startup. The first time that the app is started, this will succeed. On subsequent attempts, it will fail, and that is your clue to halt and fail to load the second instance.

You create mutexes in Windows by calling the CreateMutex function. As the linked documentation indicates, prefixing the name of the mutex with Global\ ensures that it will be visible for all terminal server sessions, which is what you want. By contrast, the Local\ prefix would make it visible only for the user session in which it was created.

int WINAPI _tWinMain(...)
{
   const TCHAR szMutexName[] = TEXT("Global\\UNIQUE_NAME_FOR_YOUR_APP");
   HANDLE hMutex = CreateMutex(NULL,        /* use default security attributes */
                               TRUE,        /* create an owned mutex           */
                               szMutexName  /* name of the mutex               */);
   if (GetLastError() == ERROR_ALREADY_EXISTS)
   {
       // The mutex already exists, meaning an instance of the app is already running,
       // either in this user session or another session on the same machine.
       // 
       // Here is where you show an instructive error message to the user,
       // and then bow out gracefully.
       MessageBox(hInstance,
                  TEXT("Another instance of this application is already running."),
                  TEXT("Fatal Error"),
                  MB_OK | MB_ICONERROR);
       CloseHandle(hMutex);
       return 1;
   }
   else
   {
       assert(hMutex != NULL);

       // Otherwise, you're the first instance, so you're good to go.
       // Continue loading the application here.
   }
}

Although some may argue it is optional, since the OS will handle it for you, I always advocate explicitly cleaning up after yourself and calling ReleaseMutex and CloseHandle when your application is exiting. This doesn't handle the case where you crash and don't have a chance to run your cleanup code, but like I mentioned, the OS will clean up any dangling mutexes after the owning process terminates.



来源:https://stackoverflow.com/questions/23579614/making-a-singleton-application-across-all-users

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!