objective-cnsrunningapplication

Find user who launched NSRunningApplication


How can I retrieve this info? Given a NSRunningApplication instance, I need to know who launched it. Activity Monitor shows this info.


Solution

  • If you just need the name of the user who launched an instance of NSRunningApplication, here's a category method that should do it:

    #import <libproc.h>
    #import <pwd.h>
    
    @implementation NSRunningApplication (UserName)
    
    - (NSString *)foo_userName {
        pid_t pid = [self processIdentifier];
        struct proc_bsdshortinfo info;
        proc_pidinfo(pid, PROC_PIDT_SHORTBSDINFO, 0, &info, sizeof(info));
        struct passwd *passwd = getpwuid(info.pbsi_uid);
        return [NSString stringWithUTF8String:passwd->pw_name];
    }
    
    @end