文章目录
一、引言
使用 xcode 进行编译的时候,有时会提醒 xpc failed,那么 xpc 是什么?这里对XPC 展开一点研究。
Access a low-level (libSystem) interprocess communication mechanism that is based on serialized property lists.
官方文档的解释为:XPC 服务API 提供一个底层(libSystem) 级别的基于序列化的 property lists 的进程间通信机制。
那么,首先我们要了解什么是 进程间通信。
二、进程间通信 IPC 与 XPC
IPC : Inter-Process Communication,进程间通信。
个人理解,所谓通信,就像打电话,核心是传递信息。进程间通信,就是两个进程间传递数据。
常见的 IPC 方法:
- 管道
- 邮槽
- 共享内存
- Socket
- URL Schema
XPC 是 OS X 下的一种 IPC 技术。
xpc传输的是一段二进制数据。
一个功能,不使用多进程也可以实现 ;但多进程 更方便将权限隔离,提高 App 的安全性和稳定性, 使得 App Sandbox 更加完备。
XPC 帮我管理了这些进程的生命周期,当我们需要与子进程通信的时候,子进程已经被 XPC 给运行起来了。
三、XPC 相关 API
和大部分 cocoa 中的 API 相似,XPC 也分为 OC 和 C 的。其中 OC 是基于 C 的封装,OC 不能保证线程安全。
1、XPC Services API (C)
使用时需要引入 #include <xpc/xpc.h>
包含文件
- xpc.h
- activity.h
- availability.h
- connection.h
- debug.h
- endpoint.h
2、the NSXPCConnection API. (OC)
存在于 Foundation 框架中存在头文件 NSXPCConnection.h
中),包含以下类:
- NSXPCInterface
- NSXPCConnection
- NSXPCListener
- NSXPCListenerEndpoint
- NSXPCProxyCreating 协议
- NSXPCListenerDelegate 代理
可以发现,基本围绕建立连接、创建监听的业务流程。
四、使用方法
1、使用 Xcode 添加 XPC 服务
添加子 target,选中 XPC 即可;
天蝎自己的名字,它会自动帮你生成xpc 协议和一系列监听代码。
target 也会自动加到主 target 的 build phases – Embed XPC Services 中.
2、自己创建 NSXPC
根据上述方式,我们可以得到标准的 XPC 协议,及接口交互监听方法;故不创建 xpc target, 也可以直接在两个target 中通过接口进行通信。
可参考:
https://github.com/smanna1729/NSXPCConnecton_SMJobBless
3、smjobbless + xpc
使用 xpc 的 C API 进行通信,可参考:
https://github.com/atnan/SMJobBlessXPC
4、iOS + NSXPC(swift)
可参考下面demo 中的 XPCClient :
https://github.com/forwardto9/XPCDemo
5、xpc+sandbox
可参考:
-
官方 App Sandbox and XPC
https://developer.apple.com/library/archive/documentation/General/Conceptual/MOSXAppProgrammingGuide/AppRuntime/AppRuntime.html#//apple_ref/doc/uid/TP40010543-CH2-SW7 -
官方demo:SandboxedFetch(sandbox下使用xpc)
https://developer.apple.com/library/archive/samplecode/SandboxedFetch/Introduction/Intro.html
五、参考
-
官文:
https://developer.apple.com/documentation/xpc?changes=_7 -
官方 Creating XPC Services
https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingXPCServices.html#//apple_ref/doc/uid/10000172i-SW6-SW1 -
rainbird : 关于mac app在sandbox下运行时的XPC Service
http://www.cocoachina.com/bbs/read.php?tid-110294.html -
开源 XPC 组件:XPCKit
https://github.com/stevestreza/XPCKit -
SMThree:macOS.XPC
https://www.jianshu.com/p/8c7e9260158d -
Objc中国:XPC
https://objccn.io/issue-14-4/ -
老谭笔记:利用XPC实现多进程之间的通信
http://www.tanhao.me/pieces/695.html/
https://stackoverflow.com/questions/14661375/nsxpcconnection-pass-an-object-by-proxy