在C ++和目标C之间进行通讯的IPC机制

Man*_*san 2 c++ ipc objective-c

我正在开发需要实现IPC机制的Mac应用程序。场景是这样的:

我的应用程序包含两个可执行文件,一个是Native Mac App(NSStatusItem app),另一个是在CPP上编码的终端应用程序。我想在这两个过程之间建立IPC通信。我希望能够从CPP向目标C发送和接收消息,反之亦然。

哪种IPC机制更适合呢?

另外,此Wiki(http://zh.wikipedia.org/wiki/Inter-process_communication#Main_IPC_methods)显示,POSIX和Windows支持IPC命名管道。我想澄清一下,如果我使用的是命名管道(我知道它是单向的),那么Mac和Objective C是否支持它?

[PS:如果可能,请提供示例代码或C ++和目标C中的IPC链接。

Sve*_*ven 5

如果您定位到Mac OS X 10.7及更高版本,则可以使用IPC的Mach服务连接来使用XPC。

在您的服务器上,创建Mach服务,设置一个事件处理程序以接受新的连接并恢复连接:

xpc_connection_t conn = xpc_connection_create_mach_service( "com.yourname.product.service", dispatch_get_main_queue(), XPC_CONNECTION_MACH_SERVICE_LISTENER );
xpc_connection_set_event_handler( conn, ^( xpc_object_t client ) {

    xpc_connection_set_event_handler( client, ^(xpc_object_t object) {
        NSLog( @"received message: %s", xpc_copy_description( object ) );

        xpc_object_t reply = xpc_dictionary_create_reply( object );
        xpc_dictionary_set_string( reply, "reply", "Back from the service" );

        xpc_connection_t remote = xpc_dictionary_get_remote_connection( object );
        xpc_connection_send_message( remote, reply );
    } );

    xpc_connection_resume( client );
}) ;

xpc_connection_resume( conn );
Run Code Online (Sandbox Code Playgroud)

我假设它正在您的具有事件循环的Cocoa应用程序中运行。如果没有事件循环,你需要确保有一个运行(NSRunloopdispatch_main(),...)

在您的客户端中,您还将创建一个不带XPC_CONNECTION_MACH_SERVICE_LISTENER标志的Mach服务连接,设置一个事件处理程序,然后恢复它。之后,您可以将消息发送到服务器并接收其答案:

xpc_connection_t conn = xpc_connection_create_mach_service( "com.yourname.product.service", NULL, 0 );
xpc_connection_set_event_handler( conn, ^(xpc_object_t object) {
    NSLog( @"client received event: %s", xpc_copy_description( object ) );
});
xpc_connection_resume( conn );

xpc_object_t message = xpc_dictionary_create( NULL, NULL, 0 );
xpc_dictionary_set_string( message, "message", "hello world" );

xpc_connection_send_message_with_reply( conn, message, dispatch_get_main_queue(), ^(xpc_object_t object) {
    NSLog( @"received reply from service: %s", xpc_copy_description( object ));
});

dispatch_main();
Run Code Online (Sandbox Code Playgroud)

请注意,要使此方法起作用,您的客户端(可能是您的情况下的命令行工具)也需要运行一个事件循环才能起作用。在我的示例中就是dispatch_main()。乍一看似乎很不方便,但这是必要且值得的。

还要注意,我的示例代码错过了所有确实必要的错误处理。

XPC API是纯C语言,因此可以在C,C ++和Objective-C中使用。您只需要使用支持块的编译器。