Get Process ID by name

We are going to use the following functions:
CreateToolhelp32Snapshot
Process32First
Process32Next
CloseHandle

Source

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <tlhelp32.h>
#define INVALID_PID_VALUE -1;
 
DWORD GetProcessID( const char * processName );
 
int main(int argc, char* argv[])
{
	DWORD pid;
 
	if(argc>1)
	{
		printf("rnSearching for the process id of '%s' ...rn", argv[1]);
 
		pid = GetProcessID(argv[1]);
 
		if (pid >= 0)
			printf("Process ID of '%s' is %urn", argv[1], pid);
	}
 
	return EXIT_SUCCESS;
}
 
DWORD GetProcessID( const char * processName ) {
	HANDLE hproc;
	PROCESSENTRY32 peProc32;
 
	peProc32.dwSize = sizeof( PROCESSENTRY32 );
 
	hproc = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
 
	if (hproc != INVALID_HANDLE_VALUE)
	{
		if (Process32First(hproc, &peProc32) == TRUE)
		{
			do
			{
				if(strcmp(processName, peProc32.szExeFile) == 0)
				{
					CloseHandle(hproc);
					return peProc32.th32ProcessID;
				}
			}
			while (Process32Next(hproc, &peProc32));
		}
	}
 
	CloseHandle(hproc);
 
	return INVALID_PID_VALUE;
}
Categories: C Tags: , , ,
%d bloggers like this: