您可以尝试如下连接它。这真的很快。
// Connect to the service, this also checks to see if it is available
mach_port_t connect_to_service ( const char * service_name )
{
mach_port_t bs_port, service_port;
kern_return_t err;
task_get_bootstrap_port ( mach_task_self (), & bs_port );
err = bootstrap_look_up ( bs_port, service_name, & service_port );
if ( err == KERN_SUCCESS )
{
return service_port;
}
else
{
return MACH_PORT_NULL;
}
}
这是我使用的完整测试。
#import <Foundation/Foundation.h>
#import <bootstrap.h>
// Connect to the service, this also checks to see if it is available
mach_port_t connect_to_service ( const char * service_name )
{
mach_port_t bs_port, service_port;
kern_return_t err;
task_get_bootstrap_port ( mach_task_self (), & bs_port );
err = bootstrap_look_up ( bs_port, service_name, & service_port );
if ( err == KERN_SUCCESS )
{
return service_port;
}
else
{
return MACH_PORT_NULL;
}
}
// Start the service
start_service ( const char * service_name, dispatch_semaphore_t s )
{
// Simulate delay
[NSThread sleepForTimeInterval:10];
mach_port_t service_port = MACH_PORT_NULL;
kern_return_t err;
err = bootstrap_check_in ( bootstrap_port, service_name, & service_port );
NSLog ( @"%s port %d err %d", service_name, service_port, err );
NSLog ( @"Server up and running - signal semaphore" );
dispatch_semaphore_signal ( s );
// Simulate running server
while ( YES )
{
[NSThread sleepForTimeInterval:60];
}
}
int main(int argc, const char * argv[])
{
@autoreleasepool
{
// insert code here...
NSLog(@"Hello, World!");
// Configuration
char * service_name = "com.hopla.test";
mach_port_t port;
// Check it
NSLog ( @"Connecting to %s that is down", service_name );
port = connect_to_service ( service_name );
NSLog ( @"%s available : %@", service_name, port == MACH_PORT_NULL ? @"NO" : @"YES" );
// The semaphore fires when the server is up, but is not used here
dispatch_semaphore_t s = dispatch_semaphore_create ( 0 );
// Starting service on background thread
dispatch_async( dispatch_queue_create( "bak",
dispatch_queue_attr_make_with_qos_class( DISPATCH_QUEUE_CONCURRENT,
QOS_CLASS_DEFAULT,
DISPATCH_QUEUE_PRIORITY_DEFAULT ) ), ^ {
NSLog ( @"Starting %s", service_name );
start_service ( service_name, s );
} );
// Repeatedly checks until the service is up
// *** do something like in this loop ***
while ( YES )
{
NSLog ( @"Connecting to %s that may be up", service_name );
port = connect_to_service ( service_name );
NSLog ( @"%s available : %@", service_name, port == MACH_PORT_NULL ? @"NO" : @"YES" );
if ( port == MACH_PORT_NULL )
{
[NSThread sleepForTimeInterval:5];
}
else
{
break;
}
}
// Final test - should be up
port = connect_to_service ( service_name );
NSLog ( @"%s fin available : %@", service_name, port == MACH_PORT_NULL ? @"NO" : @"YES" );
}
return 0;
}
我认为你应该像我在测试中那样做一些事情(在main 方法中并用***标记)。在某些后台线程上,重复检查,但如果服务器已启动,则使用适当的循环。然后,您可以发出信号量或使用完成或在服务器启动后执行任何需要完成的操作。您可以在其他地方等待信号量或任何需要的东西。