views:

177

answers:

2

I have a VC++ console app and I need to check to see if another process is running. I don't have the window title, all I have is the executable name. How do I get the process handle / PID for it? Can I enumerate the processes running with this .exe ?

+2  A: 

You can use EnumProcesses to enumerate the processes on a system.

You'll need to use OpenProcess to get a process handle, then QueryFullProcessImageName to get the processes executable.

Reed Copsey
+2  A: 

Use the CreateToolhelp32Snapshot Function

hSnapShot = FCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

Followed by Process32First and Process32Next.

You will get a PROCESSENTRY32 struct as follows with an szExeFile member.

PROCESSENTRY32W    processInfo;
processInfo.szExeFile

Make sure to first acquire the privilege SeDebugPrivilege before enumerating, that way you will get all processes across all sessions and users.

To acquire the privilege so you get all sessions:

acquirePrivilegeByName(SE_DEBUG_NAME);// SeDebugPrivilege

Where acquirePrivilegeByName is defined as:

BOOL acquirePrivilegeByName(
          const TCHAR  *szPrivilegeName)
{
    HANDLE   htoken;
    TOKEN_PRIVILEGES tkp;
    DWORD   dwerr;

    //---------------- adjust process token privileges to grant privilege
    if (szPrivilegeName == NULL)
    {
     SetLastError(ERROR_INVALID_PARAMETER);
     return FALSE;
    }

    if (!LookupPrivilegeValue(NULL, szPrivilegeName, &(tkp.Privileges[0].Luid)))
     return FALSE;

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &htoken))
     return FALSE;

    if (!AdjustTokenPrivileges(htoken, FALSE, &tkp, 0, NULL, NULL) ||
     GetLastError() != ERROR_SUCCESS) // may equal ERROR_NOT_ALL_ASSIGNED
    {
     dwerr = GetLastError();
     CloseHandle(htoken);
     SetLastError(dwerr);
     return FALSE;
    }

    CloseHandle(htoken);
    SetLastError(ERROR_SUCCESS);

    return TRUE;
} //acquirePrivilegeByName()

If you need the full process image name you can use QueryFullProcessImageName, but the szExeFile member may be enough for your needs.

Brian R. Bondy
Perfect. With source code too. Thanks!
Byron Whitlock