只允许运行一个进程

// Copyright (c) 
// All rights reserved.
//
//Describe : Only can run single program.
//Author   : Qing
//Date     : 2014-08-14

#ifndef __SINGLE_PROGRAM_H__
#define __SINGLE_PROGRAM_H__

#include <string>
#include <Windows.h>

namespace Qing
{
    class SingleProgram
    {
    public:

        SingleProgram(void) : m_Mutex(NULL)
        {
        }

        ~SingleProgram(void)
        {
            MandatoryDestoryInstance();
        }

        bool CreateSingleInstance(const std::string &ProgramName)
        {
            m_Mutex = ::CreateMutexA(NULL, TRUE, ProgramName.c_str());
            DWORD LastError =::GetLastError();

            if(m_Mutex != NULL)
            {
                ::ReleaseMutex(m_Mutex);
            }

            if(LastError == ERROR_ALREADY_EXISTS)
            {
                m_Mutex = NULL;
                return false;
            }

            return true;
        }

        void MandatoryDestoryInstance()
        {
            if(m_Mutex != NULL)
            {
                ::CloseHandle(m_Mutex);
                m_Mutex = NULL;
            }
        }

    private:

        SingleProgram(const SingleProgram&);
        SingleProgram& operator=(const SingleProgram&);

    private:

        HANDLE m_Mutex;
    };
}

#endif

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。