launchd and macOS Sessions

A question asked about how a system wide daemon process could create a notification for a user on macOS. The answer is more complicated than you might expect.
The process issuing the notification has to be running within the graphical user session of the specific user. The computer wide daemon is not within the user’s graphical session.
On macOS no user, including root
, can trivially cross graphical user sessions. A deliberate mechanism is required. This is related to the WindowServer implementation and unrelated to the operating system’s BSD UNIX heritage.
Securing the User Space
By organizing processes into root and login sessions, the launchd process is able to create a more trustworthy environment for users. Requests for Mach ports go through the launchd process, which routes the requests to the appropriate target. The login session acts like a set of walls around a user’s processes, limiting port requests to those in the current login session or root session. Doing so prevents accidental or intentional attempts by processes in a different session to obtain access to the ports in the current login session. In a sense, login sessions are a lightweight firewall around the processes they represent.
The above quote refers to older implementations of macOS, before the closed-source rewrite of launchd
.
If you are targeting recent versions of macOS, see launchd
’s bootstrap
and bootout
commands to on-demand start and stop processes within specific sessions.
launchd
is able to do this because it is the initial process and manages the sessions.
As an example of this approach, Power Manager crosses the session divide with a pmuser
process. The user process connects to the daemon and awaits instructions. This approach is involved but has worked reliably since Mac OS X 10.3+.
Useful References:
I originally published this answer on Ask Different.