0

I'm running the following code to print info about all processes currently running in the machine:

        int i = 0;
        var r = "";
        var processes = Process.GetProcesses();
        foreach (var p in processes)
        {
            try
            {
                r += $"{i}. {p.Id} {p.ProcessName} = {p.SessionId}\n";
                i++;
            }
            catch (Exception) { }
        }

        Console.WriteLine(r);

If I run the built app with admin rights I have access to all process and no exception happens, however SessionId on macOS is always zero:

0. 24976 ProcessNotifier = 0
1. 24970 mdworker_shared = 0
2. 24952 garcon = 0
3. 24951 TextMate = 0
4. 24893 com.apple.iCloudHelper = 0
5. 24770 zsh = 0
...

Is there a way to distinguish between process owners? I want to monitor processes from multiple users.

Roberto
  • 11,557
  • 16
  • 54
  • 68

1 Answers1

0

SessionId is an identifier of Terminal Services session. Terminal Services is a windows component and it doesn't make sense for MacOS. I have no idea why SessionId is always 0 on your machine. For me SessionId equals to PID in most cases.

However, SessionId is not useful in managed code on Windows as well because it doesn't allow to establish definite relation with process owning user. A call to unmanaged code (via WMI or Win32 API) can be done to get user name by SessionId or by PID like demonstrated here.

As for MacOS you can just execute external ps process in your c# code to get and parse required information:

var startInfo = new ProcessStartInfo("/bin/ps", "-eo pid,user,comm");
startInfo.RedirectStandardOutput = true;
var proc = Process.Start(startInfo);            
var output  = proc.StandardOutput.ReadToEnd();

Console.WriteLine(output);

Sample output:

PID | User Name   | Process
---------------------------------------------------------
335 | _netbios    |    /usr/sbin/netbiosd
338 | root        |    /System/Library/Frameworks/GSS.framework/Helpers/GSSCred
341 | boris       |    /usr/sbin/distnoted
342 | boris       |    /System/Library/Frameworks/LocalAuthentication.framework/Support/coreauthd
344 | boris       |    /usr/sbin/cfprefsd
345 | root        |    /usr/libexec/securityd_service
346 | boris       |    /usr/libexec/UserEventAgent
BorisR
  • 514
  • 1
  • 4
  • 19