最简service
static dispatch_queue_t process_event_queue(void) { static dispatch_queue_t _queue; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _queue = dispatch_queue_create("com.xxx.process.event.queue", DISPATCH_QUEUE_SERIAL); }); return _queue;}void event_handler(xpc_connection_t peer, xpc_object_t event) { NSDictionary* info = [NSDictionary dictionaryWithXPCObject:event]; xpc_object_t reply = [info XPCObject]; xpc_connection_send_message(peer, reply);}int main(int argc, const char * argv[]) { @autoreleasepool { xpc_connection_t service = xpc_connection_create_mach_service("com.xxx.uem.uem-agent", dispatch_get_main_queue(), XPC_CONNECTION_MACH_SERVICE_LISTENER); if (service) { xpc_connection_set_event_handler(service, ^(xpc_object_t _Nonnull peer) { xpc_type_t type = xpc_get_type(peer); if (type == XPC_TYPE_CONNECTION) { // TODO: validate the peer connection xpc_connection_set_target_queue(peer, process_event_queue()); xpc_connection_set_event_handler(peer, ^(xpc_object_t _Nonnull object) { event_handler(peer, object); }); xpc_connection_resume(peer); } }); xpc_connection_resume(service); dispatch_main(); } } return 0;}
最简client
#import <Foundation/Foundation.h>#import "ObjectToXPC/ObjectToXPC.h"int main(int argc, const char * argv[]) { @autoreleasepool { xpc_connection_t connection; connection = xpc_connection_create_mach_service("com.xxx.uem.uem-agent", NULL, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED); if (connection) { xpc_connection_set_event_handler(connection, ^(xpc_object_t _Nonnull object) { if (xpc_get_type(object) == XPC_TYPE_ERROR) { NSLog(@"XPC Error: %s", xpc_copy_description(object)); } else { NSDictionary* info = [NSDictionary dictionaryWithXPCObject:object]; NSLog(@"info: %@", info); } }); } xpc_connection_resume(connection); NSDictionary* message = @{@"name" : @"zhaorui"}; xpc_connection_send_message(connection, [message XPCObject]); dispatch_main(); } return 0;}
launchd.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>Label</key> <string>com.xxx.uem.uem-agent</string> <key>KeepAlive</key> <true/> <key>Program</key> <string>/Users/xxx/uem-agent/build/Debug/uem-agent</string> <key>ProgramArguments</key> <array> <string>/Users/xxx/uem-agent/build/Debug/uem-agent</string> </array> <key>MachServices</key> <dict> <key>com.xxx.uem.uem-agent</key> <true/> </dict></dict></plist>
三方库
https://github.com/rastersize/ObjectToXPC