xsmscb 发表于 2017-7-9 11:32:10

OS X background process

  Types of Background Process
  1. login item
  2. xpc service
  3. daemon/agent (也可以叫 mach service)
  4. startup item
  login item
  login items 是 OS X 对需要开机运行的APP推荐的启动方式,当用户登录之后自动调起程序,配置 login item 有两种方式:
  1) LSSharedFileListInsertItemURL() 或者 系统偏好设置->用户和群组>登录项
  通过这种方式,login item 会被保存在路径: ~/Library/Preferences/com.apple.loginitems.plist
  2) Service Management Framework
  方式1不可以在 sand box 中使用,Service Management Framework 可以,但是他要求 app 有一个 helper 程序。
  helper 程序存放在 app 的 Contents/Library/LoginItems 目录下,app 的主程序通过在运行时调用 SMLoginItemSetEnabled() 函数来设置 helper 程序为自启动程序,helper 程序在自启动后则可以调起其他程序。
  另外,方式2只适用于 app 被保存在 /Applications/ 路径下的情形。
  xpc service
  1. XPC是什么?
  XPC 是 OS X 下的一种 IPC (进程间通信) 技术, 它实现了权限隔离, 可以配合 sand box 使用。
  XPC 机制通过以 NSXPCConnection 作为 channel 进行通信,而 connection 两端分别为 client 和 listener。
  listener 通过 NSXPCListener 监听来自 client 的连接,通信双方分别通过 exportedInterface(listener) 和 remoteObjectInterface(client) 交换各自要求对方实现的接口。
  基于 OC 语言的动态特性,通信双方在调用通信接口时,操作更类似于 OC 中的消息传递(messaging structure),这也是其区别于其他 IPC 技术的一个特征。
  2. 为什么使用 xpc service ?    
  使用 xpc service,可以将 app 拆分为『主进程+XPC服务』的模式,通过这种模式并配合 sand box 就可以针对 APP 实现错误隔离和权限隔离。
  另外,xpc service 的生命周期都由 launchd 来进行控制,当 xpc service 在接收消息时 crash 了,其对应的 connection 依然直有效,但是这个未被处理的消息需要主进程重新发送请求。

  daemon/agent
  daemon 和 agent 都是由 launchd 进程负责启动的后台作业。
  根据安装路径,可以细分为:
  1. ~/Library/LaunchAgents: 每个用户私有的agent
  2. /Library/LaunchAgents: 所有用户共有的agent
  3. /Library/LaunchDaemons: 所有用户共有的 daemon,具有root权限
  4. /System/Library/LaunchAgents: 系统配置的 agent
  5. /System/Library/LaunchDaemons: 系统配置的 daemon
  daemon/agent 通过 plist 文件(property list)进行编程并存入上文所描述的路径中。
  如何编写和配置 plist,可以参考:
  http://www.launchd.info/
  https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man5/launchd.plist.5.html
  注:通过下图可知,当 daemon 调起有 UI 程序时,会以 agent 的权限调起 UI 程序。

  startup item
  根据官方文档,这个方式将在以后被废弃,有兴趣可以去看官方文档。另外,想找这方面的实例可以去参考 cisco 的 anyconnect,它使用的就是 startup item 来配置程序的自启动。
  https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/StartupItems.html
  其他参考:
  http://www.codesec.net/view/219693.html
  https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/Introduction.html
  https://developer.apple.com/library/content/technotes/tn2083/_index.html
  https://objccn.io/issue-14-4/
页: [1]
查看完整版本: OS X background process