文章目錄
一、引言
使用 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