可以使用像IPC这样的Mac OS X XPC在进程之间交换消息吗?怎么样?

poo*_*per 20 macos ipc xpc sandbox osx-lion

根据Apple的说法,Lion中引入的新XPC服务API提供了一种轻量级机制,用于与Grand Central Dispatch(GCD)集成并启动的基本进程间通信.

似乎可以将此API用作一种IPC,如POSIX IPC,但是,我找不到如何做到这一点.

我正在尝试使用XPC API传递两个进程,因此我可以在它们之间传递消息,但我总是在服务器端出现"XPC连接无效"错误.

我不想要XPC服务,我只想使用客户端 - 服务器架构交换消息.

我使用两个类似BSD的进程,所以没有Info.plist或者其他什么......

我一直关注这个讨论http://lists.macosforge.org/pipermail/launchd-dev/2011-November/000982.html但是这个主题看起来有点模糊和无证.

谢谢!

Dan*_*ert 17

是的,这是可能的,但不是你期望的方式.

不能让(非启动)流程提供服务.这是出于安全原因,因为这样可以轻松地进行中间人攻击.

但是,您仍然可以实现您想要的功能:您必须设置一个推出XPC/mach服务的launchd服务.然后,进程A和B都连接到您的launchd服务.然后,进程A可以创建一个所谓的匿名连接,并将其发送到launchd服务,然后将其转发到进程B.一旦发生这种情况,进程A和B可以直接通过该连接相互通信(即,launchd服务可以退出没有断开连接).

这可能看似四处,但出于安全原因这是必要的.

xpc_object(3)有关匿名连接的详细信息,请参见手册页.

这有点反直觉,因为进程A将创建一个侦听器对象xpc_connection_create().然后,A 从侦听器创建一个端点对象,xpc_endpoint_create()并通过线路(通过XPC)将该端点发送到进程B.然后,B可以将该对象转换为连接xpc_connection_create_from_endpoint().然后,侦听器的事件处理程序将接收与B创建的连接匹配的连接对象xpc_connection_create_from_endpoint().这与xpc_connection_create_mach_service()客户端连接时将接收连接对象的事件处理程序的方式类似.


Arv*_*vin 11

以下是我使用XPC进行双向IPC的方法.

Helper(登录项)是服务器或监听器.主应用程序或任何其他应用程序被视为客户端.

我创建了以下经理:

标题:

@class CommXPCManager;

typedef NS_ENUM(NSUInteger, CommXPCErrorType) {

    CommXPCErrorInvalid     = 1,
    CommXPCErrorInterrupted = 2,
    CommXPCErrorTermination = 3
};

typedef void (^XPCErrorHandler)(CommXPCManager *mgrXPC, CommXPCErrorType errorType, NSError *error);
typedef void (^XPCMessageHandler)(CommXPCManager *mgrXPC, xpc_object_t event, NSDictionary *message);
typedef void (^XPCConnectionHandler)(CommXPCManager *peerConnection);

@interface CommXPCManager : NSObject

@property (readwrite, copy, nonatomic) XPCErrorHandler errorHandler;
@property (readwrite, copy, nonatomic) XPCMessageHandler messageHandler;
@property (readwrite, copy, nonatomic) XPCConnectionHandler connectionHandler;

@property (readonly, nonatomic) BOOL clientConnection;
@property (readonly, nonatomic) BOOL serverConnection;
@property (readonly, nonatomic) BOOL peerConnection;

@property (readonly, nonatomic) __attribute__((NSObject)) xpc_connection_t connection;

@property (readonly, strong, nonatomic) NSString *connectionName;
@property (readonly, strong, nonatomic) NSNumber *connectionEUID;
@property (readonly, strong, nonatomic) NSNumber *connectionEGID;
@property (readonly, strong, nonatomic) NSNumber *connectionProcessID;
@property (readonly, strong, nonatomic) NSString *connectionAuditSessionID;

- (id) initWithConnection:(xpc_connection_t)aConnection;
- (id) initAsClientWithBundleID:(NSString *)bundleID;
- (id) initAsServer;

- (void) suspendConnection;
- (void) resumeConnection;
- (void) cancelConnection;

- (void) sendMessage:(NSDictionary *)dict;
- (void) sendMessage:(NSDictionary *)dict reply:(void (^)(NSDictionary *replyDict, NSError *error))reply;
+ (void) sendReply:(NSDictionary *)dict forEvent:(xpc_object_t)event;

@end
Run Code Online (Sandbox Code Playgroud)

执行:

@interface CommXPCManager ()
@property (readwrite, nonatomic) BOOL clientConnection;
@property (readwrite, nonatomic) BOOL serverConnection;
@property (readwrite, nonatomic) BOOL peerConnection;
@property (readwrite, strong, nonatomic) __attribute__((NSObject)) dispatch_queue_t dispatchQueue;
@end

@implementation CommXPCManager

@synthesize clientConnection, serverConnection, peerConnection;
@synthesize errorHandler, messageHandler, connectionHandler;
@synthesize connection    = _connection;
@synthesize dispatchQueue = _dispatchQueue;

#pragma mark - Message Methods:

- (void) sendMessage:(NSDictionary *)dict {

    dispatch_async( self.dispatchQueue, ^{

        xpc_object_t message = dict.xObject;
        xpc_connection_send_message( _connection, message );
        xpc_release( message );
    });
}

- (void) sendMessage:(NSDictionary *)dict reply:(void (^)(NSDictionary *replyDict, NSError *error))reply {

    dispatch_async( self.dispatchQueue, ^{

        xpc_object_t message = dict.xObject;
        xpc_connection_send_message_with_reply( _connection, message, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(xpc_object_t object) {

            xpc_type_t type = xpc_get_type( object );

            if ( type == XPC_TYPE_ERROR ) {

                /*! @discussion Reply: XPC Error */
                reply( [NSDictionary dictionary], [NSError errorFromXObject:object] );

            } else if ( type == XPC_TYPE_DICTIONARY ) {

                /*! @discussion Reply: XPC Dictionary */
                reply( [NSDictionary dictionaryFromXObject:object], nil );
            }
        }); xpc_release( message );
    });
}

+ (void) sendReply:(NSDictionary *)dict forEvent:(xpc_object_t)event {

    xpc_object_t message = [dict xObjectReply:event];
    xpc_connection_t replyConnection = xpc_dictionary_get_remote_connection( message );
    xpc_connection_send_message( replyConnection, message );
    xpc_release( message );
}

#pragma mark - Connection Methods:

- (void) suspendConnection {

    dispatch_async(self.dispatchQueue, ^{ xpc_connection_suspend( _connection ); });
}

- (void) resumeConnection {

    dispatch_async(self.dispatchQueue, ^{ xpc_connection_resume(_connection); });
}

- (void) cancelConnection {

    dispatch_async(self.dispatchQueue, ^{ xpc_connection_cancel(_connection); });
}

#pragma mark - Accessor Overrides:

- (void) setDispatchQueue:(dispatch_queue_t)queue {

    if ( queue ) dispatch_retain( queue );
    if ( _dispatchQueue ) dispatch_release( _dispatchQueue );
    _dispatchQueue = queue;

    xpc_connection_set_target_queue( self.connection, self.dispatchQueue );
}

#pragma mark - Getter Overrides:

- (NSString *) connectionName {

    __block char* name = NULL;
    dispatch_sync(self.dispatchQueue, ^{ name = (char*)xpc_connection_get_name( _connection ); });

    if(!name) return nil;
    return [NSString stringWithCString:name encoding:[NSString defaultCStringEncoding]];
}

- (NSNumber *) connectionEUID {

    __block uid_t uid = 0;
    dispatch_sync(self.dispatchQueue, ^{ uid = xpc_connection_get_euid( _connection ); });
    return [NSNumber numberWithUnsignedInt:uid];
}

- (NSNumber *) connectionEGID {

    __block gid_t egid = 0;
    dispatch_sync(self.dispatchQueue, ^{ egid = xpc_connection_get_egid( _connection ); });
    return [NSNumber numberWithUnsignedInt:egid];
}

- (NSNumber *) connectionProcessID {

    __block pid_t pid = 0;
    dispatch_sync(self.dispatchQueue, ^{ pid = xpc_connection_get_pid( _connection ); });
    return [NSNumber numberWithUnsignedInt:pid];
}

- (NSNumber *) connectionAuditSessionID{ 

    __block au_asid_t auasid = 0;
    dispatch_sync(self.dispatchQueue, ^{ auasid = xpc_connection_get_asid( _connection ); });
    return [NSNumber numberWithUnsignedInt:auasid];
}

#pragma mark - Setup Methods:

- (void) setupConnectionHandler:(xpc_connection_t)conn {

    __block CommXPCManager *this = self;

    xpc_connection_set_event_handler( conn, ^(xpc_object_t object) {

        xpc_type_t type = xpc_get_type( object );

        if ( type == XPC_TYPE_ERROR ) {

            /*! @discussion Client | Peer: XPC Error */

            NSError *xpcError = [NSError errorFromXObject:object];

            if ( object == XPC_ERROR_CONNECTION_INVALID ) {

                if ( this.errorHandler )
                    this.errorHandler( this, CommXPCErrorInvalid, xpcError );

            } else if ( object == XPC_ERROR_CONNECTION_INTERRUPTED ) {

                if ( this.errorHandler )
                    this.errorHandler( this, CommXPCErrorInterrupted, xpcError );

            } else if ( object == XPC_ERROR_TERMINATION_IMMINENT ) {

                if ( this.errorHandler )
                    this.errorHandler( this, CommXPCErrorTermination, xpcError );
            }

            xpcError = nil; return;

        } else if ( type == XPC_TYPE_CONNECTION ) {

            /*! @discussion XPC Server: XPC Connection */

            CommXPCManager *xpcPeer = [[CommXPCManager alloc] initWithConnection:object];

            if ( this.connectionHandler )
                this.connectionHandler( xpcPeer );

            xpcPeer = nil; return;

        } else if ( type == XPC_TYPE_DICTIONARY ) {

            /*! @discussion Client | Peer: XPC Dictionary */

            if ( this.messageHandler )
                this.messageHandler( this, object, [NSDictionary dictionaryFromXObject:object] );
        }

    });
}

- (void) setupDispatchQueue {

    dispatch_queue_t queue = dispatch_queue_create( xpc_connection_get_name(_connection), 0 );
    self.dispatchQueue = queue;
    dispatch_release( queue );
}

- (void) setupConnection:(xpc_connection_t)aConnection {

    _connection = xpc_retain( aConnection );

    [self setupConnectionHandler:aConnection];
    [self setupDispatchQueue];
    [self resumeConnection];
}

#pragma mark - Initialization:

- (id) initWithConnection:(xpc_connection_t)aConnection {

    if ( !aConnection ) return nil;

    if ( (self = [super init]) ) {

        self.peerConnection = YES;
        [self setupConnection:aConnection];

    } return self;
}

- (id) initAsClientWithBundleID:(NSString *)bundleID {

    xpc_connection_t xpcConnection = xpc_connection_create_mach_service( [bundleID UTF8String], nil, 0 );

    if ( (self = [super init]) ) {

        self.clientConnection = YES;
        [self setupConnection:xpcConnection];
    }

    xpc_release( xpcConnection );
    return self;
}

- (id) initAsServer {

    xpc_connection_t xpcConnection = xpc_connection_create_mach_service( [[[NSBundle mainBundle] bundleIdentifier] UTF8String],
                                                                         dispatch_get_main_queue(),
                                                                         XPC_CONNECTION_MACH_SERVICE_LISTENER );
    if ( (self = [super init]) ) {

        self.serverConnection = YES;
        [self setupConnection:xpcConnection];
    }

    xpc_release( xpcConnection );
    return self;
}

@end
Run Code Online (Sandbox Code Playgroud)

显然,我正在使用一些自我解释的类别方法.例如:

@implementation NSError (CategoryXPCMessage)
+ (NSError *) errorFromXObject:(xpc_object_t)xObject {

    char *description = xpc_copy_description( xObject );
    NSError *xpcError = [NSError errorWithDomain:NSPOSIXErrorDomain code:EINVAL userInfo:@{
                         NSLocalizedDescriptionKey:
                        [NSString stringWithCString:description encoding:[NSString defaultCStringEncoding]] }];
    free( description );
    return xpcError;
}
@end
Run Code Online (Sandbox Code Playgroud)

好的,使用这个我为客户端和服务器端设置了一个接口.标题看起来像这样:

@class CommXPCManager;

@protocol AppXPCErrorHandler <NSObject>
@required
- (void) handleXPCError:(NSError *)error forType:(CommXPCErrorType)errorType;
@end

static NSString* const kAppXPCKeyReturn = @"AppXPCInterfaceReturn";    // id returnObject
static NSString* const kAppXPCKeyReply  = @"AppXPCInterfaceReply";     // NSNumber: BOOL
static NSString* const kAppXPCKeySEL    = @"AppXPCInterfaceSelector";  // NSString
static NSString* const kAppXPCKeyArgs   = @"AppXPCInterfaceArguments"; // NSArray (Must be xObject compliant)

@interface AppXPCInterface : NSObject

@property (readonly, strong, nonatomic) CommXPCManager *managerXPC;
@property (readonly, strong, nonatomic) NSArray *peerConnections;

- (void) sendMessage:(SEL)aSelector withArgs:(NSArray *)args reply:(void (^)(NSDictionary *replyDict, NSError *error))reply;
- (void) sendMessageToPeers:(SEL)aSelector withArgs:(NSArray *)args reply:(void (^)(NSDictionary *replyDict, NSError *error))reply;

- (id) initWithBundleID:(NSString *)bundleID andDelegate:(id<AppXPCErrorHandler>)object forProtocol:(Protocol *)proto;
- (id) initListenerWithDelegate:(id<AppXPCErrorHandler>)object forProtocol:(Protocol *)proto;

- (void) observeListenerHello:(CommReceptionistNoteBlock)helloBlock;
- (void) removeListenerObserver;

- (void) startClientConnection;
- (void) startListenerConnection;
- (void) stopConnection;

@end
Run Code Online (Sandbox Code Playgroud)

以下是启动侦听器的实现:

- (void) startListenerConnection {

    [self stopConnection];
    self.managerXPC = [[CommXPCManager alloc] initAsServer];

    __block AppXPCInterface *this = self;

    self.managerXPC.connectionHandler = ^(CommXPCManager *peerConnection) {

        [(NSMutableArray *)this.peerConnections addObject:peerConnection];

        peerConnection.messageHandler = ^(CommXPCManager *mgrXPC, xpc_object_t event, NSDictionary *message) {

            [this processMessage:message forEvent:event];
        };

        peerConnection.errorHandler = ^(CommXPCManager *peer, CommXPCErrorType errorType, NSError *error) {

            [this processError:error forErrorType:errorType];
            [(NSMutableArray *)this.peerConnections removeObject:peer];
        };
    };

    [CommReceptionist postGlobalNote:kAppXPCListenerNoteHello];
}
Run Code Online (Sandbox Code Playgroud)

以下是启动客户端的实现:

- (void) startClientConnection {

    [self stopConnection];
    self.managerXPC = [[CommXPCManager alloc] initAsClientWithBundleID:self.identifierXPC];

    __block AppXPCInterface *this = self;

    self.managerXPC.messageHandler = ^(CommXPCManager *mgrXPC, xpc_object_t event, NSDictionary *message) {

        [this processMessage:message forEvent:event];
    };

    self.managerXPC.errorHandler = ^(CommXPCManager *mgrXPC, CommXPCErrorType errorType, NSError *error) {

        [this processError:error forErrorType:errorType];
    };
}
Run Code Online (Sandbox Code Playgroud)

现在这是事情的顺序.

  1. 您的主应用程序启动其帮助程序帮助程序使用其bundleID <---重要开始侦听!
  2. 主应用程序侦听全局通知,然后发送消息
  3. 当客户端发送消息时,建立连接

现在服务器可以向客户端发送消息,客户端可以向服务器发送消息(有或没有回复).

它非常快,运行良好,专为OS X 10.7.3或更高版本而设计.

几点说明:

  • 帮助程序的名称必须与程序包ID的名称相同
  • 该名称必须以您的团队ID开头
  • 对于沙盒,Main app和Helper app应用程序组设置必须以帮助程序Bundle ID的前缀开头

例如,Helper bundle id是:ABC123XYZ.CompanyName.GroupName.Helper App Group ID将是:ABC123XYZ.CompanyName.GroupName

我遗漏了其他细节,以免引起任何人的伤害.但如果仍然不清楚只是问我会回答.

好的,希望这有帮助.阿尔文

  • @Arvin你可以提供完整的实现,因为这个参考看起来像是网络上最有希望的来源.任何与项目的github链接都会非常有用.我知道OSX 10.8我们有NSXPCConnection我可以从apple找到很好的参考,但我的项目要求是支持10.7.5及更高版本.谢谢. (2认同)

A O*_*A O 7

对于一直在努力解决这个问题的人来说,我终于能够100%地在两个应用程序进程之间进行通信 NSXPCConnection

需要注意的关键是,您只能创建NSXPCConnection三件事.

  1. 一个XPCService.您可以严格通过名称连接到XPCService
  2. 马赫服务.您还可以通过名称严格连接到Mach服务
  3. NSXPCEndpoint.这是我们正在寻找的,在两个应用程序进程之间进行通信.

问题是我们不能直接NSXPCListenerEndpoint从一个应用程序转移到另一个应用程序.

它涉及创建一个拥有属性的machservice Launch Agent(请参阅此示例以了解如何执行此操作)NSXPCListenerEndpoint.一个应用程序可以连接到machservice,并将该属性设置为自己的属性[NSXPCListener anonymousListener].endpoint

然后另一个应用程序可以连接到machservice,并请求该端点.

然后使用该端点,NSXPCConnection可以创建一个,成功建立了两个应用程序之间的桥梁.我已经测试了来回发送对象,这一切都按预期工作.

请注意,如果您的应用程序是沙盒,必须XPCService在Application和Machservice之间创建一个中间人

我很高兴我的工作 - 我在SO中相当活跃,所以如果有人对源代码感兴趣,只需添加评论,我就可以努力发布更多细节

我遇到的一些障碍:

你必须启动你的机器服务,这些是线路:

   OSStatus                    err;
   AuthorizationExternalForm   extForm;

   err = AuthorizationCreate(NULL, NULL, 0, &self->_authRef);
   if (err == errAuthorizationSuccess) {
      NSLog(@"SUCCESS AUTHORIZING DAEMON");
   }
   assert(err == errAuthorizationSuccess);

   Boolean             success;
   CFErrorRef          error;

   success = SMJobBless(
                        kSMDomainSystemLaunchd,
                        CFSTR("DAEMON IDENTIFIER HERE"),
                        self->_authRef,
                        &error
                        );
Run Code Online (Sandbox Code Playgroud)

此外,每次重建守护程序时,都必须使用以下bash命令卸载以前的启动代理程序:

sudo launchctl unload /Library/LaunchDaemons/com.example.apple-samplecode.EBAS.HelperTool.plist
sudo rm /Library/LaunchDaemons/com.example.apple-samplecode.EBAS.HelperTool.plist
sudo rm /Library/PrivilegedHelperTools/com.example.apple-samplecode.EBAS.HelperTool
Run Code Online (Sandbox Code Playgroud)

(当然,使用相应的标识符)

  • 刚试过它,它应该为您构建并运行 (2认同)
  • 它已经很长时间了:\但我记得并推荐的是你进入SMJobBlessUtil脚本,并找到它抛出该错误的位置.然后提出一堆`print`语句,这样你就可以调试脚本,看看你究竟缺少了什么以及为什么(通过查看脚本并看看它在做什么)祝你好运并报告回来! (2认同)
  • 很高兴听到你找到了成功:)我记得花了几个星期把它弄清楚 - 没有资源帮助,最后让它上班很棒 (2认同)
  • IIRC我们最终选择了`NSConnection`,有太多的箍要让XPC去工作@StefanSzekeres (2认同)
  • 是的@StefanS我记得那个应用程序,IIRC它只是帮助你在应用程序和服务之间设置XPC连接,而不是在应用程序和应用程序之间.然而那是很久以前的事了,我对自己的记忆并不自信 (2认同)