简体   繁体   中英

macOS : programmatic check if process runs as a launchDaemon or launchAgent or from command-line

I'd like to get an indication about the context in which my process is running from. I'd like to distinguish between the following cases:

  1. It runs as a persistent scheduled task (launchDaemon/launchAgent)
  2. It was called on-demand and created by launchd using open command-line or double-click.
  3. It was called directly from command-line terminal (ie > /bin/myProg from terminal )

Perhaps is there any indication about the process context using Objective-c/swift framework or any other way? I wish to avoid inventing the wheel here:-)

thanks

There is definetely no simple public API or framework for doing this, and doing this is hard.

Some parts of this info possibly could be retreived by your process itslef with some side-ways which will work on some system versions:

  • There is a launchctl C-based API , which you can try to use to enumerate all launch daemon/agent tasks and search for your app path/pid. You may require a root rights for your process for doing this.

  • Using open command-line sometimes could be traced with environment variables it sets for your process.

  • Running directly from command-line could leave responsible_pid filled correctly (which is private API from libquarantine, unless you are observing it with Endpoint Security starting from 11.smth version)

All this things, except launchctl API, are not public, not reliable, could be broken at any time by Apple, and may be not sufficient for your needs.

But it it worth to take them a try, because there is nothing better:)

You could potentially distinguish all cases you want using system events monitoring from some other (root-permitted) process you control, possibly adopting Endpoint Security Framework (requires an entitlement from Apple, can't be distributed via AppStore), calling a lot of private APIs and a doing bunch of reversing tricks.

The open resource I could suggest on this topic is here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM