How can I have a script automatically ran when I start or stop an app without using 3rd party tools?
I'm not developing the application myself, it's a general question that applies to any installed apps.
Clarifications: The application is started/quit be any means possible. The script and the application should be ran serially.
Best Answer
Assuming answers to my clarification questions above are that you want:
...there may be a few ways to do it. None I can think of are terribly elegant or turnkey and all require some sort of demonized process running as root which act to monitor the system for launch events.
Monitoring
exec
calls viafs_usage
One possible way is to create a daemon (LaunchDaemon) which runs continuously, monitoring a running
fs_usage
command forexec
events. You can see the kind of information you get by running the following command:Here's the relevant line when I opened Safari:
Here's the output when I opened ran
open /Applications/Maps.app
from the command line:Note that nearly all "Applications" (/Applications/*.app) are launched via
posix_spawn
bylaunchd
and the file used to launch them is/Applications/FOO.app/Contents/MacOS/FOO
(whereFOO
is the application's name). So, theoretically, you could have your LaunchDaemon monitoring this command and triggering your script whenever it outputs the path to the app you're monitoring:Monitoring
launchservicesd
vialsappinfo
I wasn't terribly happy with the above because it's kinda hacky, watching for filesystem events instead of the launching event that triggered them. And then I realized, "
launchd
"! Enter Launch Services:Leading to:
And VoilĂ , you not only have launching, but also get notified when an app quits. The keys you care about are the following: