Windows 对象私有命名空间的使用,以前的笔记
#include "pch.h"
#include <iostream>
#include <windows.h>
#include <Sddl.h> // ConvertStringSecurityDescriptorToSecurityDescriptor
#include <strsafe.h> // StringCchPrintf
int main()
{
HANDLE p_hBoundary = NULL;
PCTSTR g_szBoundary = TEXT("my-Boundary");
p_hBoundary = CreateBoundaryDescriptor(g_szBoundary, 0);
BYTE localAdminSID[SECURITY_MAX_SID_SIZE];
DWORD cbSID = sizeof(localAdminSID);
if (!CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, localAdminSID, &cbSID))
std::cout << "创建一个SID(安全描述符)出错\n";
if (!AddSIDToBoundaryDescriptor(&p_hBoundary, localAdminSID))
std::cout << "添加SID到边界描述符出错\n";
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = FALSE;
if (!ConvertStringSecurityDescriptorToSecurityDescriptor(TEXT("D:(A;;GA;;;BA)"), SDDL_REVISION_1, &sa.lpSecurityDescriptor, NULL))
std::cout << "创建安全描述符出错\n";
PCTSTR g_szNamespace = TEXT("my-Namespace");
HANDLE g_hNamespace = CreatePrivateNamespace(&sa, p_hBoundary, g_szNamespace);
LocalFree(sa.lpSecurityDescriptor);
DWORD dwLastError = GetLastError();
if (g_hNamespace == NULL) {
if (dwLastError == ERROR_ACCESS_DENIED) {
std::cout << "拒绝访问,请以管理员方式运行\n";
std::cin.get();
return 0;
}
else {
if (dwLastError == ERROR_ALREADY_EXISTS) {
g_hNamespace = OpenPrivateNamespace(p_hBoundary, g_szNamespace);
if (g_hNamespace == NULL) {
std::cout << "打开私有命名空间失败\n";
std::cin.get();
return 0;
}
}
else {
std::cout << "打开私有命名空间失败\n";
std::cin.get();
return 0;
}
}
}
TCHAR sz_MutexName[64];
StringCchPrintf(sz_MutexName, _countof(sz_MutexName), TEXT("%s\\%s"), g_szNamespace, TEXT("Singletion"));
HANDLE g_hSingleton = CreateMutex(NULL, FALSE, sz_MutexName);
if (GetLastError() == ERROR_ALREADY_EXISTS) {
CloseHandle(g_hSingleton); //不清理计数的话 如果运行失败 必须等待程序关闭 才能运行,因为我们是控制台,下面我加了cin.get,所以这里提前关闭这个handle
std::cout << "程序已经在运行了\n";
std::cin.get();
return 1;
}
else {
std::cout << "运行成功\n";
std::cin.get();
return 0;
}
}