您的位置:首页 > 其它

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

2011-11-09 22:37 295 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: