Windows 对象私有命名空间的使用

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


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

没事干写博客玩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值