Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Session ID of another process in C++

When I start my application, I try to figure out if there is another process of the application. I also try to figure out if it runs in a different user session.

So far so good, that's what it looks like in C#:

    private static bool isThereAnotherInstance() {
        string name = Path.GetFileNameWithoutExtension(Application.ExecutablePath);
        Process[] pAll = Process.GetProcessesByName(name);
        Process pCurrent = Process.GetCurrentProcess();
        foreach (Process p in pAll) {
            if (p.Id == pCurrent.Id) continue;
            if (p.SessionId != pCurrent.SessionId) continue;
            return true;
        }
        return false;
    }

But the requirements has changed, I need this piece of code in C++ using plain WinAPI.

Until now, I'm able to find a process that has the same executable path by using CreateToolhelp32Snapshot, OpenProcess, etc.

The missing part is how to get the session id of a process (current and other processes, AND current and other session)
How to do this?

like image 234
joe Avatar asked Dec 31 '25 01:12

joe


1 Answers

The ProcessIdToSessionId function maps a process ID to a session ID.

You note that this seems to require excessive permissions that aren't needed by .Net.

.Net does get some of its process data from HKEY_PERFORMANCE_DATA in the registry, but this doesn't include the session ID. The session ID is obtained using NtQuerySystemInformation to return an array of SYSTEM_PROCESS_INFORMATION structures. This structure is not well documented, but the session ID immediately follows the handle count (i.e. it is the field currently declared as BYTE Reserved4[4];). Microsoft do not guarantee that this will continue to be true in future versions of Windows.

like image 185
arx Avatar answered Jan 01 '26 16:01

arx