2

I have a launchd agent which is a companion to another tool. When it runs, it checks if the tool is ready before proceeding. I want to add an extra case in which the launchd will also remove itself if the tool no longer exists.

This methodology is in use across a range of separate tools. As such, I make them as cookie-cutter as possible.

I can tell the launchd agent plist to delete itself by adding its full path and editing it every time for every tool, but is there a better way? Is there (for example) a variable I could grab where the launchd returns its own name or path?

Also open to other methods which would allow a launchd agent to uninstall itself. It is important that it does not need to call a tool which does not ship with a standard installation of macOS, as that would defeat the point.

1 Answer 1

0

I can tell the launchd agent plist to delete itself by adding its full path and editing it every time for every tool, but is there a better way?

I am unaware of any launchd .plist setting/command that will allow it to "delete itself."

When your Mac boots and when you load a .plist, launchd scans (as applicable): /Library/LaunchAgents, ~/Library/LaunchAgents, /Library/LaunchDaemons, /System/Library/LaunchAgents and /System/Library/LaunchDaemons. If the .plist isn't there, it doesn't load.

So, if you "check to see if the tool exists and remove itself" you'll need to incorporate that logic as part of the script that's kicked off by launchd.

Is there (for example) a variable I could grab where the launchd returns its own name or path?

launchd doesn't return "its own name or path;" it loads/unloads/launches/stops a job defined by a .plist at a path. Therefore, if you want that variable to be available, you'll need to set it as part of the environment defined in the .plist.

That said, I don't believe it possible that you can both have a job running and simultaneously unload it especially by itself; more so if it requires elevated privileges to do so. This is probably why install/uninstall requires user intervention.

Additionally, per the man page for launchd.plist it addresses agents/daemons accessing "protected" files/folders:

CAVEATS

Daemons and agents managed by launchd are subject to macOS user privacy protections. Specifying privacy sensitive files and folders in a launchd plist may not have the desired effect, and may prevent the job from running.

By having an agent call a script that in effect deletes itself (from one of the directories listed above) may have unintended consequences and may not even run.

1
  • Even if the job can’t unload itself it can still delete its own file. Meaning that on next reboot it does unload itself.
    – user137369
    Feb 20, 2023 at 20:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .