WIN32核心编程 - 进程操作(二) 遍历进程 - 进程通信

目录

遍历进程

CreateToolhelp32Snapshot

EnumProcesses

NtQuerySystemInformation

进程通信

clipboard

FileMapping

NamedPipe

Mailslot


遍历进程

CreateToolhelp32Snapshot

#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>

int main()
{
	HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hSnap != INVALID_HANDLE_VALUE)
	{
		setlocale(LC_ALL, "chs");
		PROCESSENTRY32 pe32 = { 0 };
		pe32.dwSize = sizeof(pe32);

		BOOL bRet = Process32First(hSnap, &pe32);
		while (bRet)
		{
			wprintf(L"%s %d\r\n", pe32.szExeFile, pe32.th32ProcessID);
			if (lstrcmp(pe32.szExeFile, L"die.exe") == 0)
			{
				HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
				if (hProcess != NULL)
				{
					TerminateProcess(hProcess, 0);
					CloseHandle(hProcess);
				}
			}
			bRet = Process32Next(hSnap, &pe32);
		}

		CloseHandle(hSnap);
	}

	return 0;
}

EnumProcesses

#include <iostream>
#include <Windows.h>
#include <Psapi.h>

int main()
{
	DWORD dwProcessCount = 0;
	DWORD dwProcessIdArr[1024] = { 0 };
	if (!EnumProcesses(dwProcessIdArr, sizeof(dwProcessIdArr), &dwProcessCount))
	{
		return 0;
	}

	for (size_t i = 0; i < dwProcessCount / 4; i++)
	{
		printf("ProcessId -> [%d] \r\n", dwProcessIdArr[i]);
		HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessIdArr[i]);
		if (hProcess != NULL)
		{
			DWORD dwModuleCount = 0;
			HMODULE hMod = NULL;
			if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &dwModuleCount))
			{
				TCHAR szName[MAX_PATH] = { 0 };
				if (GetModuleBaseName(hProcess, hMod, szName, sizeof(szName) / sizeof(TCHAR)))
				{
					printf("%ws \r\n", szName);
				}
			}
		}

	}

	return 0;
}

NtQuerySystemInformation

  #include <iostream>
#include <Windows.h>

/*
	NTSTATUS
	NtQuerySystemInformation(
	__in SYSTEM_INFORMATION_CLASS SystemInformationClass,
	__out_bcount_opt(SystemInformationLength) PVOID SystemInformation,
	__in ULONG SystemInformationLength,
	__out_opt PULONG ReturnLength
	);
*/
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
#define SystemProcessInformation 5
typedef LONG KPRIORITY;
typedef NTSTATUS(WINAPI* NtQuerySystemInformation)(DWORD, PVOID, ULONG, PULONG);
typedef struct _UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;    
    PWCH   Buffer;
} UNICODE_STRING;
typedef struct _SYSTEM_PROCESS_INFORMATION {
    ULONG NextEntryOffset;
    ULONG NumberOfThreads;
    LARGE_INTEGER SpareLi1;
    LARGE_INTEGER SpareLi2;
    LARGE_INTEGER SpareLi3;
    LARGE_INTEGER CreateTime;
    LARGE_INTEGER UserTime;
    LARGE_INTEGER KernelTime;
    UNICODE_STRING ImageName;
    KPRIORITY BasePriority;
    HANDLE UniqueProcessId;
    HANDLE InheritedFromUniqueProcessId;
    ULONG HandleCount;
    ULONG SessionId;
    ULONG_PTR PageDirectoryBase;
    SIZE_T PeakVirtualSize;
    SIZE_T VirtualSize;
    ULONG PageFaultCount;
    SIZE_T PeakWorkingSetSize;
    SIZE_T WorkingSetSize;
    SIZE_T QuotaPeakPagedPoolUsage;
    SIZE_T QuotaPagedPoolUsage;
    SIZE_T QuotaPeakNonPagedPoolUsage;
    SIZE_T QuotaNonPagedPoolUsage;
    SIZE_T PagefileUsage;
    SIZE_T PeakPagefileUsage;
    SIZE_T PrivatePageCount;
    LARGE_INTEGER ReadOperationCount;
    LARGE_INTEGER WriteOperationCount;
    LARGE_INTEGER OtherOperationCount;
    LARGE_INTEGER ReadTransferCount;
    LARGE_INTEGER WriteTransferCount;
    LARGE_INTEGER OtherTransferCount;
} SYSTEM_PROCESS_INFORMATION, * PSYSTEM_PROCESS_INFORMATION;

int main()
{
    NTSTATUS status = NULL;
	HMODULE hModule = NULL;
    ULONG uLength = 0xFFFFF;
    ULONG uRet = 0;
    NtQuerySystemInformation pFun  = NULL;
    PSYSTEM_PROCESS_INFORMATION pInfo = NULL;

	//NtQuerySystemInformation
	hModule = LoadLibrary(TEXT("ntdll.dll"));
	pFun = (NtQuerySystemInformation)GetProcAddress(hModule, "NtQuerySystemInformation");
    pInfo = (PSYSTEM_PROCESS_INFORMATION)malloc(uLength);
    status = pFun(SystemProcessInformation, pInfo, uLength, &uRet);
    if (NT_SUCCESS(status))
    {
        while (pInfo->NextEntryOffset)
        {
            printf("%ws %d \r\n", pInfo->ImageName.Buffer, pInfo->UniqueProcessId);
            pInfo = (PSYSTEM_PROCESS_INFORMATION)((PUCHAR)pInfo + pInfo->NextEntryOffset);
        }
    }
	return 0;
}

进程通信

clipboard

#include <iostream>
#include <Windows.h>

int main()
{
	//CTRL C
	#if 0
	const char* str = "Hello 0xCC";

	//打开剪贴板 OpenClipboard
	if (!OpenClipboard(NULL)) return 0;

	//清空剪贴板 EmptyClipboard
	if (!EmptyClipboard())
	{
		CloseClipboard();
		return 0;
	}

	//分配内存区 GlobalAlloc
	HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, strlen(str) + 1);
	if (hMem == NULL)
	{
		CloseClipboard();
		return 0;
	}

	PVOID pBuffer = GlobalLock(hMem);
	if (pBuffer == NULL)
	{
		CloseClipboard();
		return 0;
	}

	memcpy(pBuffer, str, strlen(str) + 1);
	GlobalUnlock(hMem);

	//设置剪贴板 SetClipboard
	SetClipboardData(CF_TEXT, hMem);

	//关闭剪贴板 CloseClipboard
	CloseClipboard();
	#endif 

	//CTRL V
	#if 0
	//打开剪贴板 OpenClipboard
	if (!OpenClipboard(NULL)) return 0;

	//获取剪贴板 GetClipboardData
	HANDLE hData = GetClipboardData(CF_TEXT);
	if (hData == NULL)
	{
		CloseClipboard();
		return 0;
	}

	PCHAR pStr = (PCHAR)GlobalLock(hData);
	std::cout << pStr << std::endl;
	GlobalUnlock(hData);

	//关闭剪贴板 CloseClipboard
	CloseClipboard();
	
	#endif

	return 0;
}

FileMapping

#include <iostream>
#include <windows.h>

int main()
{
	//创建文件映射对象
	HANDLE hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,0xFF,TEXT("0xCCShare"));
	if (hMapFile == NULL)
	{
		std::cout << "CreateFileMapping ErrorCode -> " << GetLastError() << std::endl;
		return 0;
	}

	//映射对象视图
	LPVOID lpBuffer = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
	if (lpBuffer == NULL)
	{
		std::cout << "MapViewOfFile ErrorCode -> " << GetLastError() << std::endl;
		return 0;
	}

	//写入共享内存数据
	char szStr[] = "Exit";
	memcpy(lpBuffer, szStr, sizeof(szStr));

	//等待进程读取
	std::cout << "Success Share Mem " << std::endl;
	std::cin.get();

	//释放资源
	UnmapViewOfFile(lpBuffer);
	CloseHandle(hMapFile);

	return 0;
}
#include <iostream>
#include <windows.h>

int main()
{
	//打开存在文件映射对象
	HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, TEXT("0xCCShare"));
	if (hMapFile == NULL)
	{
		std::cout << "OpenFileMapping ErrorCode -> " << GetLastError() << std::endl;
		return 0;
	}

	//映射对象视图
	LPVOID lpBuffer = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
	if (lpBuffer == NULL)
	{
		std::cout << "MapViewOfFile ErrorCode -> " << GetLastError() << std::endl;
		return 0;
	}

	std::cout << "Read Info -> " << static_cast<char*>(lpBuffer) << std::endl;
	std::cin.get();

	//获取共享内存数据
	if (strcmp((PCHAR)lpBuffer, "Exit") == 0)
	{
		ExitProcess(0);
	}

	//释放资源
	std::cout << "Free" << std::endl;
	UnmapViewOfFile(lpBuffer);
	CloseHandle(hMapFile);

	return 0;
}

NamedPipe

#include <iostream>
#include <Windows.h>

#define PIPE_NAME L"\\\\.\\pipe\\0xCCPipe"

int main()
{
	//创建命名管道
	HANDLE hNamedPipe = CreateNamedPipe(
		PIPE_NAME,
		PIPE_ACCESS_DUPLEX,
		PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
		PIPE_UNLIMITED_INSTANCES,
		4096,
		4096,
		NMPWAIT_USE_DEFAULT_WAIT,
		NULL);
	if (hNamedPipe == INVALID_HANDLE_VALUE)
	{
		std::cout << "CreateNamedPipe ErrorCode -> " << GetLastError() << std::endl;
		return 0;
	}

	//等待客户连接
	std::cout << "Waiting for client Connection" << std::endl;
	BOOL bRet = ConnectNamedPipe(hNamedPipe, NULL);
	if (!bRet)
	{
		std::cout << "ConnectNamedPipe ErrorCode -> " << GetLastError() << std::endl;
		CloseHandle(hNamedPipe);
		return 0;
	}
	std::cout << "Client Connected" << std::endl;

	//发送客户消息
	DWORD dwWrite = 0;
	char szBuffer[] = "Hello 0xCC";
	WriteFile(hNamedPipe, szBuffer, sizeof(szBuffer), &dwWrite, NULL);

	//接受客户消息
	CHAR szBuffer1[0xFF] = { 0 };
	DWORD dwRead = 0;
	ReadFile(hNamedPipe, szBuffer1, sizeof(szBuffer1), &dwRead, NULL);
	std::cout << szBuffer1 << std::endl;

	//清理资源
	CloseHandle(hNamedPipe);

	return 0;
}
#include <iostream>
#include <Windows.h>

#define PIPE_NAME L"\\\\.\\pipe\\0xCCPipe"

int main()
{
	//连接命名管道
	HANDLE hNamedPipe = CreateFile(
		PIPE_NAME,
		GENERIC_READ | GENERIC_WRITE,
		0,
		NULL,
		OPEN_EXISTING,
		NULL,
		NULL
	);
	if (hNamedPipe == INVALID_HANDLE_VALUE)
	{
		std::cout << "CreateNamedPipe ErrorCode -> " << GetLastError() << std::endl;
		return 0;
	}

	//接受服务消息
	CHAR szBuffer[0xFF] = { 0 };
	DWORD dwRead = 0;
	ReadFile(hNamedPipe, szBuffer, sizeof(szBuffer), &dwRead, NULL);
	std::cout << szBuffer << std::endl;

	//发送服务消息
	DWORD dwWrite = 0;
	char szBuffer1[] = "Hello 0xCC";
	WriteFile(hNamedPipe, szBuffer1, sizeof(szBuffer1), &dwWrite, NULL);

	//清理资源
	CloseHandle(hNamedPipe);

	return 0;
}

Mailslot

#include <iostream>
#include <windows.h>

int main() 
{
    //创建邮槽
    HANDLE hMailSlot = CreateMailslot(
        TEXT("\\\\.\\mailslot\\0xCCMailSlot"),
        0,
        MAILSLOT_WAIT_FOREVER,
        NULL
    );
    if (hMailSlot == INVALID_HANDLE_VALUE) return 0;

    //读取邮槽
    while (TRUE)
    {
        DWORD dwRead = 0;
        char szBuffer[0xFF] = { 0 };
        BOOL bRet = ReadFile(hMailSlot, szBuffer, sizeof(szBuffer), &dwRead, NULL);
        if (!bRet) break;
        std::cout << szBuffer << std::endl;
    }

    //清理资源
    CloseHandle(hMailSlot);
    
    return 0;
}
#include <iostream>
#include <Windows.h>

int main()
{
	// 打开邮槽
	HANDLE hMailSlot = CreateFile(
		TEXT("\\\\.\\mailslot\\0xCCMailSlot"),
		GENERIC_READ | GENERIC_WRITE,
		FILE_SHARE_READ,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL
	);
	if (hMailSlot == INVALID_HANDLE_VALUE) return 0;

	// 写入邮槽
	DWORD dwWrite = 0;
	char szBuffer[] = "Hello 0xCC";
	WriteFile(hMailSlot, szBuffer, sizeof(szBuffer), &dwWrite, NULL);

	//清理资源
	CloseHandle(hMailSlot);

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值