Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the UserName of the owner of a process?

Tags:

c#

.net

process

I'm trying to get a list of processes currently owned by the current user (Environment.UserName). Unfortunately, the Process class doesn't have any way of getting the UserName of the user owning a process.

How do you get the UserName of the user which is the owner of a process using the Process class so I can compare it to Environment.UserName?

If your solution requires a pinvoke, please provide a code example.

like image 774
Andrew Moore Avatar asked Nov 18 '08 22:11

Andrew Moore


People also ask

How do I find the process owner?

Open the terminal window or app. To see only the processes owned by a specific user on Linux run: ps -u {USERNAME} Search for a Linux process by name run: pgrep -u {USERNAME} {processName} Another option to list processes by name is to run either top -U {userName} or htop -u {userName} commands.

How do I find my PID username?

The /proc/<pid>/loginuid file has the uid number of the user running the process; id -nu reads uid from stdin and returns a user name. Nice.

Which command will find all processes owned by user?

To view all processes on the system, you can execute:ps -f.


2 Answers

Thanks, your answers put me on the proper path. For those who needs a code sample:

public class App
{
    public static void Main(string[] Args)
    {
        Management.ManagementObjectSearcher Processes = new Management.ManagementObjectSearcher("SELECT * FROM Win32_Process");

        foreach (Management.ManagementObject Process in Processes.Get()) {
            if (Process["ExecutablePath"] != null) {
                string ExecutablePath = Process["ExecutablePath"].ToString();

                string[] OwnerInfo = new string[2];
                Process.InvokeMethod("GetOwner", (object[]) OwnerInfo);

                Console.WriteLine(string.Format("{0}: {1}", IO.Path.GetFileName(ExecutablePath), OwnerInfo[0]));
            }
        }

        Console.ReadLine();
    }
}
like image 183
Andrew Moore Avatar answered Sep 27 '22 21:09

Andrew Moore


The CodeProject article How To Get Process Owner ID and Current User SID by Warlib describes how to do this using both WMI and using the Win32 API via PInvoke.

The WMI code is much simpler but is slower to execute. Your question doesn't indicate which would be more appropriate for your scenario.

like image 37
Martin Hollingsworth Avatar answered Sep 27 '22 21:09

Martin Hollingsworth