1

How do I detect that I'm running as a LaunchAgent under launchd on Mac OS X?

This is for a program (written in Go) that needs to restart when told to do so. If it's been started from a terminal or init script, it needs to do this by itself. If running under a service manager it should not attempt to restart but simply exit and be restarted by the manager.

For example, when running under Solaris SMF the environment variable SMF_FMRI is set, but I see nothing similar in launchd.

There are obvious workarounds (require a command line flag to be used or an environment variable to be set) but I'm interested in an "automatic" solution.

(This is not a duplicate of the similar sounding question How to check if launchd has started the script?)

Community
  • 1
  • 1
Jakob Borg
  • 23,685
  • 6
  • 47
  • 47

1 Answers1

2

Get your Parent Process Id (PPID) and compare it with the PID of launchd.

In the screen grab, you can see launchd's PID is 41840 (in red) and the PPIDs of mdflagwriter, distnoted and cfprefsd (in blue) match that number, so they were launched by launchd.

enter image description here

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • Excellent! I hope so. I have never tried it on OSX, but that's what I always used to do on Solaris, IRIX, HP-UX. Maybe add a comment if it goes well, so we all learn something! – Mark Setchell Mar 12 '14 at 09:30