Starting/stopping a launchd agent for all users with GUI sessions

喜欢而已 提交于 2019-11-27 22:20:47

Using launchctl bsexec is correct, but you need to launch a wrapper tool which drops UID to the target user before running the 'real' agent executable. Oh, and it's probably better to look for loginwindow processes, as those are the leaders of the login sessions (though launchd is very likely to work too).

It looks like per-user launchd instances are running not in the same bootstrap namespace as launchctl launched from Terminal.

By using Dock.app as pid donor and some sudo magic:

ps aux | grep Dock.app | grep -v grep | awk '{system("sudo launchctl bsexec "$2" sudo -u "$1" launchctl load -S Aqua /Library/LaunchAgents/com.my.agent.plist")}'

it is possible to launch agent in all running sessions.

Not neat, but works.

Update: will not work on 10.7. Yes, agent will be launched, but as I can see from tests not in the correct context.

Based on the discussions here and this script, I didn't think a wrapper tool should be necessary. These two bash scripts may help others too.

Unload Agents

#!/bin/bash
for id in `ps aux | grep -v grep | grep MyAgent | awk {'print $2'}`
do
    launchctl bsexec $id launchctl unload /Library/LaunchAgents/myAgent.plist
done

Replace 'MyAgent' with the name of your Launch Agent.

Load Agents

#!/bin/bash
for pid_uid in $(ps -axo pid,uid,args | grep -i "[l]oginwindow.app" | awk '{print $1 "," $2}'); do

    pid=$(echo $pid_uid | cut -d, -f1)
    uid=$(echo $pid_uid | cut -d, -f2)

    launchctl bsexec "$pid" chroot -u "$uid" / launchctl load /Library/LaunchAgents/myAgent.plist
done

Called from a root daemon, this will load and unload the Launch Agent referenced in myAgent.plist for all logged-in users.

Note that due to 'rootless' in OS X El Capitan (10.11), the use of bsexec may no longer work, but up to 10.10, this should be fine.

I had the same problem. To solve this, use a pid "under" launchd, the pid of a process that launchd has started.

The pid you commit to 'launchctl bsexec' is used to find the right bootstrap. If you use the pid of launchd (from the user context) than you work in the root launchd bootstrap. If you use pe. the Finder or the Dock pid of the user, you can work in this "per-user" bootstrap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!