I'm about to tear my hair out over this. My solution still has major problems. If a user logs out of his account and logs into another (rare but it happens), the app stops working again. When this happens even restarting the app doesn't fix it.
I have spent 2 days trying to get this to work now. Does anybody have any idea why there is such a big problem communicating with System Events from within LC?
EDIT: Ok, more info. The issue only happens when the app is loaded as a launch daemon. I confirmed it with a sample stack. And it also does not happen with a shell script that is running as a daemon. This is rather complicated, but here goes:
I created a standalone app that has a field with the applescript and a button to run it, and the result it displayed below it. Compiled as a standalone app. The app works fine when run normally. The app works fine when run as root (sudo <binary inside app bundle>).
Created a plist to load the app as a launch daemon. Loaded it with launchctl (sudo launchctl load -F <plist>). App opens fine, but gets errors when running the applescript unless "System Events" is already running and owned by logged in user.
To confirm that the issue was specific to LC and not just demonized processes in general, I wrote a short shell script to do the same thing:
Code: Select all
#!/bin/sh
sleep 5; osascript -e 'tell application "System Events" to return the name of every process whose frontmost is true' >> test.txt
Then I made a plist to load the script as a launch daemon. Loaded it with launchctl (sudo launchctl load -F <plist>). It works fine, outputs the frontmost process into the text file every 5 seconds.
So what this tells me is that a shell script daemon can talk to system events on its own, but LC cannot (under these circumstances). I'm sure there is a good reason for this, but it is beyond my understanding. If anyone knows of a solution, I'd appreciate it, but I know it's a long shot!