#include <windows.h>
#include <psapi.h>
#include <stdio.h>
int PrintProcessNameAndID( DWORD processID, const char *name )
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
&cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
if(strcmp(szProcessName, name) == 0) // right process
{
CloseHandle(hProcess);
return 1;
}
// Release the handle to the process.
CloseHandle( hProcess );
return 0;
}
int find(const char *name)
{
// Get the list of process identifiers.
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
{
return -1;
}
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
// Print the name and process identifier for each process.
for ( i = 0; i < cProcesses; i++ )
{
if( aProcesses[i] != 0 )
{
if(PrintProcessNameAndID( aProcesses[i], name ))
{
//found it
return aProcesses[i];
}
}
}
return -1;
}
int main(int argc, char **argv)
{
if(argc < 2){ /* Check if we have two parameters on the command line, including the program name */
printf("Usage: Process name required \n");
exit(1);
}
int pid = find(argv[1]);
if (pid!=-1)
{
HANDLE hProcess = OpenProcess(STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE, FALSE, (DWORD)pid);
if (NULL != hProcess )
{
DWORD dwWaitResult = WaitForSingleObject (hProcess, INFINITE);
CloseHandle( hProcess );
return 0;
}
}
return 1;
}