【发布时间】:2022-10-12 22:17:19
【问题描述】:
使用XPC 处理我的第一个 macOS 启动代理。
我需要提供服务的进程由launchd 启动,然后保持运行直到发出初始调用的客户端进程关闭。
我在启动代理的plist 中将KeepAlive 设置为true,但显然这意味着即使在进行初始调用的客户端进程结束后,该进程仍然存在。
在launchd.plist(5) 的文档中,它指出“可以指定条件字典来选择性地控制是否启动
让工作保持活力”......有人知道这里指的是什么字典以及如何实施这些条件吗?
编辑
为上下文添加代码,尽管我会强调这一切都可以正常工作并且行为符合我的预期(设置连接以启动服务)。
感谢 rderik 提供示例代码 (https://github.com/rderik/rdConsoleSequencer)。
// Connecting to the service from the client...
let connection = NSXPCConnection(machServiceName: "com.name.servicename")
connection.remoteObjectInterface = NSXPCInterface(with: MyXPCProtocol.self)
connection.resume()
let service = connection.remoteObjectProxyWithErrorHandler { error in
print("Received error:", error)
} as? MyXPCProtocol
// Service main.swift ...
let listener = NSXPCListener(machServiceName:
"com.name.servicename")
let delegate = ServiceDelegate()
listener.delegate = delegate;
listener.resume()
RunLoop.main.run()
// Service class...
@objc class MyXPC: NSObject, MyXPCProtocol {
// My service functions...
}
// Service delegate...
class ServiceDelegate: NSObject, NSXPCListenerDelegate {
func listener(_ listener: NSXPCListener, shouldAcceptNewConnection newConnection: NSXPCConnection) -> Bool {
let exportedObject = MyXPC()
newConnection.exportedInterface = NSXPCInterface(with: MyXPCProtocol.self)
newConnection.exportedObject = exportedObject
newConnection.resume()
return true
}
}
// Service protocol
@objc(MyXPCProtocol) protocol MyXPCProtocol {
// My protocol functions...
}
// User LaunchAgents plist...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>com.name.MyXPC</string>
<key>Program</key>
<string>/mypath.../</string>
<key>MachServices</key>
<dict>
<key>com.name.myservice</key>
<true/>
</dict>
</dict>
</plist>
【问题讨论】:
-
请单击edit 并添加足够的代码和您的
plist文件,以便人们为您提供帮助。
标签: swift macos launchd xpc launch-agent