1

I have a launchdaemon that is successfully loaded post installation of an app. I want the launchdaemon to load the launchagent in the user context. How can this be achieved on 10.10? Is the following way accurate and approved by Apple.

sudo launchctl bsexec "$PID" sudo -u "$USER" launchctl load /Library/LaunchAgents/pathto.plist

Concerns:

  1. Is the above way Apple approved? I hope it doesn't get break with OS upgrades?
  2. Also for confirmation, how can launchdaemon get the values of the PID and USER. Would running the following command from the launchdaemon in root context fetch the accurate logged in user: /usr/bin/who | /usr/bin/awk '/console/{print $1;exit}'

Any help will be appreciable.

ZestyZest
  • 911
  • 13
  • 27

1 Answers1

1

This is what I mostly do. I am not sure whether this is an approved and accepted coding by Apple.

I use the command given below to get logged n user name. If multiple users are logged in it gives the name of the active user, I mean the active console user.

stat -f%Su /dev/console

LaunchAgent can be loaded from LaunchDaemon using su -l. You just need the logged in user name as parameter.

    NSString *userName;
    NSTask *task = [[NSTask alloc]init];
    NSPipe *pipe = [NSPipe pipe];

    [task setLaunchPath:@"/usr/bin/stat"];
    [task setArguments:[NSArray arrayWithObjects:@"-f%Su", @"/dev/console", nil]];
    [task setStandardOutput:pipe];
    [task launch];
    [task waitUntilExit];
    userName = [[NSString alloc] initWithData:[[pipe fileHandleForReading] readDataToEndOfFile]
                                        encoding:NSUTF8StringEncoding];


    NSString *loggedInUserName = [userName stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

    NSString *loadScript = [NSString stringWithFormat: @"su -l %@ -c \"/bin/launchctl load /Library/LaunchAgents/com.abc.appname.plist\"", loggedInUserName];
    system([loadScript UTF8String]);

A word of caution. I have seen this causing problems problems in LaunchAgent accessing UI (anything related to WindowServer) when we have set RunAtLoad as YES in OS versions 10.9 and below. I have never faced this in 10.10.

Seema Kadavan
  • 2,538
  • 1
  • 16
  • 31
  • Thanks for your reply. Is there any event or mechanism which you leverage to know if the user has logged in or not as LaunchDaemon would automatically be loaded on boot. – ZestyZest Apr 23 '15 at 07:12
  • Check this out - http://stackoverflow.com/questions/23266781/daemon-to-know-when-a-user-logs-into-the-mac. – Seema Kadavan Apr 23 '15 at 09:34