良好的程序应该有自我诊断能力

Good Design的程序应该会报告程序自己的状态,例如内存的堆与栈的使用情况。。。。

 

// Check by opening a global mutex; if the mutex exists, then an applicaiton using the same name is already running.

BOOL IsUniqueInstanceInSystem(LPCWSTR Name)
{
	// simple mechanism to ensure single instance
	WCHAR MutexName[MAX_PATH];
	BOOL retValue = FALSE;

	const errno_t error=wcsncpy_s(MutexName, _countof(MutexName), Name, CTSTRLEN(MutexName));
	ABSASSERT(error==0); // The buffer was not copied.  
	MutexName[CTSTRLEN(MutexName)]='\0';

    OSVERSIONINFO OSversion;
    
    OSversion.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
    GetVersionEx(&OSversion);

    switch(OSversion.dwPlatformId)
    {
       case VER_PLATFORM_WIN32_NT:
         if (OSversion.dwMajorVersion >= 5)  
         {
			// Specify that this is a system mutex rather than a Terminal Services session mutex
			errno_t error;
			error=wcsncpy_s(MutexName, _countof(MutexName), L"Global\\", CTSTRLEN(MutexName));
			ABSASSERT(error==0); // The buffer was not copied.  
			ABSASSERT(wcslen(Name)<=_countof(MutexName)-1-wcslen(MutexName));
			error=wcsncat_s(MutexName, _countof(MutexName), Name, _countof(MutexName)-1-wcslen(MutexName));
	}
        break;
    }

    // try to open mutex with presctibed name, unique to our application
    HANDLE hMutex = OpenMutexW(MUTEX_MODIFY_STATE, 0, MutexName);
    if (hMutex)
    {
        // Allow a few seconds to let the previous instance (if any) to
        // terminate before a new one is started.  Otherwise, user attempt
        // to start more than one session a time.
        CloseHandle (hMutex);
        Sleep (5000);
        hMutex = OpenMutexW(MUTEX_MODIFY_STATE, 0, MutexName);
    }

	if (!hMutex)
	{
		// otherwise, we are the first instance, so we can create the Mutex and continue
		PSECURITY_DESCRIPTOR pSD; 
 		// Initialize a security descriptor.  
 		pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);   
		if (pSD != NULL) 
		{ 
			if (InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) 
			{
				// Add a NULL descriptor ACL to the security descriptor.  
				if (SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE)) 
				{

					SECURITY_ATTRIBUTES sec_attr;
					sec_attr.nLength=sizeof(SECURITY_ATTRIBUTES);
					sec_attr.lpSecurityDescriptor=pSD;
					sec_attr.bInheritHandle=TRUE;

					hMutex = CreateMutexW(&sec_attr, TRUE, MutexName);
				}
			}

			LocalFree((HLOCAL) pSD); 
		}

		retValue = (hMutex != NULL);
	}

	return retValue;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值