SMJobBless works only with kSMDomainSystemLaunchd, need kSMDomainUserLaunchd

548 Views Asked by At

The documentations states, that with SMJobBless you can use only kSMDomainSystemLaunchd

SMJobBless(kSMDomainSystemLaunchd, (CFStringRef)label, authRef, (CFErrorRef *)error);

But how to create a LaunchAgent inside LaunchAgents/ in users library, that executes on user login using SMJobBless or similar approach?

1

There are 1 best solutions below

0
On

This is an old question, but maybe someone has the same issue.

There are 2 main approaches to add an agent: using system API (ServiceManagement framework) or command-line tool (launchctl).

Using API

SMJobBless creates a daemon—process, running under root. If you wish to create an agent—process, running under another user, use the SMLoginItemSetEnabled function. There is a slight difference between these functions:

  1. SMJobBless registers an executable and SMLoginItemSetEnabled accepts bundle id as main parameter, so for an agent you need to create a Cocoa app.

  2. SMLoginItemSetEnabled is much easier to set up.

  3. SMJobBless copies the executable to Library/PrivilegedHelperTools and launches it from there, not from your bundle. SMLoginItemSetEnabled launches the agent from your bundle, without copying it.

  4. SMJobBless requires the user to enter admin password; SMLoginItemSetEnabled doesn't bother the user with anything, it does not require root rights.

Using launchctl

SMLoginItemSetEnabled registeres the agent only for the current user. If you need to add an agent, which will be launched automatically for any user, that logges in, put a configuration .plist file into /Library/LaunchAgents (you'll need root rights to do that). In order to load it immediately use launchctl tool (from code—via NSTask). Documentation on configuration files: man launchd.plist.