现在的位置: 首页 > 综合 > 正文

互斥量实现单exe实例运行

2017年12月11日 ⁄ 综合 ⁄ 共 1521字 ⁄ 字号 评论关闭

说明:需要同路径下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 object

CWinApp 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;
}

抱歉!评论已关闭.