めいくりぷとのブログ

技術的なことをまったりと。

プロセスを列挙する。

typedef struct _PROCESS_INFO
{
	WCHAR ImageName[MAX_PATH / 4];
	ULONG UniqueProcess;
}PROCESS_INFO, *PPROCESS_INFO;

typedef std::vector<PROCESS_INFO> PROCESS_LIST;

// src
BOOL EnumerateProcess(__out PROCESS_LIST &ProcessList)
{
	NTSTATUS ntStatus;
	PVOID	 pBuffer;
	ULONG	 uLength;
	SYSTEM_PROCESS_INFORMATION *pProcessInformation;

	uLength				= sizeof(SYSTEM_PROCESS_INFORMATION);
	pProcessInformation = reinterpret_cast<SYSTEM_PROCESS_INFORMATION*>(malloc(uLength));

	ntStatus = NtQuerySystemInformation(SystemProcessInformation, 
										pProcessInformation, 
										uLength, 
										&uLength);

	if (ntStatus == STATUS_INFO_LENGTH_MISMATCH)
		pBuffer = malloc(uLength);

	if (pBuffer != NULL)
	{
		if (NT_SUCCESS(NtQuerySystemInformation(
				SystemProcessInformation, 
				pBuffer, 
				uLength, 
				NULL)))
		{
			pProcessInformation = reinterpret_cast<SYSTEM_PROCESS_INFORMATION*>(pBuffer);

			while (pProcessInformation != NULL
				&& pProcessInformation->NextEntryOffset > 0)
			{
				if (pProcessInformation->UniqueProcessId != 0 &&
					pProcessInformation->ImageName.Buffer != NULL)
				{
					PROCESS_INFO Info;
					StringCchPrintf(Info.ImageName,
						pProcessInformation->ImageName.Length, _T("%s"),
						pProcessInformation->ImageName.Buffer);
					Info.UniqueProcess = reinterpret_cast<ULONG>(pProcessInformation->UniqueProcessId);
					ProcessList.push_back(Info);
				}

				pProcessInformation = reinterpret_cast<SYSTEM_PROCESS_INFORMATION*>(
					PBYTE(pProcessInformation) + pProcessInformation->NextEntryOffset);
			}
		}

		free(pBuffer);
	}

	return (!ProcessList.empty());
}

結果:
f:id:mcrypt:20180329221833p:plain