简体   繁体   English

如何在 Mac 上的 C# 中区分进程的用户

[英]How to distinguish process' users in C# on Mac

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:如果我使用管理员权限运行构建的应用程序,我可以访问所有进程并且不会发生任何异常,但是 macOS 上的 SessionId 始终为零:

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.我想监控来自多个用户的进程。

SessionId is an identifier of Terminal Services session. SessionId 是终端服务会话的标识符。 Terminal Services is a windows component and it doesn't make sense for MacOS.终端服务是一个 Windows 组件,它对 MacOS 没有意义。 I have no idea why SessionId is always 0 on your machine.我不知道为什么 SessionId 在你的机器上总是 0。 For me SessionId equals to PID in most cases.对我来说 SessionId 在大多数情况下等于 PID。

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.但是,SessionId 在 Windows 上的托管代码中也没有用,因为它不允许与拥有进程的用户建立明确的关系。 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 .非托管代码(通过WMI或的Win32 API)调用可以做到通过会话ID或PID来获得用户名像展示在这里

As for MacOS you can just execute external ps process in your c# code to get and parse required information:至于 MacOS,你可以在你的 c# 代码中执行外部ps进程来获取和解析所需的信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM