互斥量实现单exe实例运行

来源:互联网 发布:淘宝卖家版下载官方 编辑:程序博客网 时间:2024/05/01 12:30

说明:需要同路径下exe只有一个实例运行,不同路径下同名exe不互相影响。

技术实现:使用内核对象mutex实现进程间互斥。


vs2005创建win32工程(支持MFC),字符集为unicode。

// MutexTest.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "MutexTest.h"#ifdef _DEBUG#define new DEBUG_NEW#endif// The one and only application objectCWinApp theApp;HANDLE m_hMutex;using namespace std;//获取互斥量名称CString GetMutexName();int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]){    int nRetCode = 0;    CString strMutexName = GetMutexName();    m_hMutex = CreateMutex(NULL, TRUE, strMutexName);    // 检测是否已经创建Mutex    // 如果已经创建,就终止进程的启动    if ((m_hMutex != NULL) && (GetLastError() == ERROR_ALREADY_EXISTS))      {        ReleaseMutex(m_hMutex);        return nRetCode;    }    // initialize MFC and print and error on failure    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))    {        // TODO: change error code to suit your needs        _tprintf(_T("Fatal Error: MFC initialization failed\n"));        nRetCode = 1;    }    else    {        // TODO: code your application's behavior here.    }    wcout<<(const TCHAR*)strMutexName<<endl;    Sleep(10000);    if (m_hMutex != NULL)    {        ReleaseMutex(m_hMutex);        CloseHandle(m_hMutex);    }    return nRetCode;}void GetModulePath(CString& strPath){    TCHAR szFileNames[260];    //获取主模块的绝对路径    DWORD dwLen = GetModuleFileName(NULL, szFileNames, sizeof(szFileNames));    for(DWORD offset=dwLen; offset>=0; offset--)    {        if(szFileNames[offset] == '\\')        {            szFileNames[offset] = '\0';            break;        }    }    strPath = szFileNames;    strPath += "\\";}CString GetMutexName(){    //不同路径下名称相同的exe可同时运行    CString strModePath = _T("");    GetModulePath(strModePath);    strModePath.TrimRight(_T("\\"));    CString strMutexName = strModePath + _T("\\CSingletonApp");    strMutexName.Replace(_T("\\"), _T("+"));    return strMutexName;}