Find user who launched NSRunningApplication

494 views Asked by At

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

3

There are 3 answers

5
Wevah On BEST ANSWER

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
4
bbum On

From the documentation on NSRunningApplication: Only user applications are tracked; this does not provide information about every process on the system.

I.e. it won't give you all the processes on the system.

The closest you can do is grab the runningApplications from NSWorkspace. But that'll be an incomplete list.

Alternatively, you can dive down to the same APIs the system uses in Activity Monitor. But that'll be painful. Or you could launch ps auxwww from NSTask and parse the output, also painful.

0
Motti Shneor On

NSRunningApplication class will only give you instances of apps run by the CURRENT USER. If multiple users are concurrently logged in to the Mac, each running their own Applications, NSRunningApplication will NOT provide the list of running apps for all the logged in users. Only the apps of the calling user.

That said, the OP’s question translates to “what is my user name” because any NSRunningApplication instance will be owned and run by that user,

An important side note - NSRunningApplication only returns the main processes of bundled apps. It will NOT provide sub processes (XPC services,login items, daemons agents, command-line tools etc). Many apps today delegate most of their work to one of these subprocesses and will not be captured.