I ran into this issue a few times, usually in .NET code. In plain Win32 it is a bit easier to determine a process owner than in .NET. (Unless one uses WMI which is very slow and completely unusable if you have dozens or more processes to look into.)
One problem is that OpenProcessToken often returns an Access Denied. In that case another method must be used to obtain the process owner. Luckily a Google search revealed such a method.
The result appears to work, at least well enough for my purposes. I am actually using both methods in a C# program but found it much easier to implement both in C without the marshal (just using the sheriff, haha).
This program uses the helper functions I introduced in the last blog entry.
A few notes:
- I have no idea why OpenProcessToken() returns an Access Denied sometimes and neither has anybody else.
- The program has no proper error checking. The output can be quite fantastic (for example very Chinese) when, as happened to me often, the process queried does not exist. I do not check the contents of the szName string if the system calls didn't fill it.
- I guess a long is signed and a DWORD is not. This might not work if you have too many processes.
- I cannot even remember how often I confused SDs (Security Descriptors) with SIDs (Security Identifiers).
I purposefully did not provide a copy-and-paste-able version because my code is full of errors and oversights and definitely therefor SHOULD NOT be used by people who copy and paste code from the Internet. If instead you copy the code by hand, you have a running chance of finding mistakes and not copy them. Do that! And tell me my mistakes.