如何异步获取xpc结果超时

时间:2020-06-29 17:20:27

标签: dispatch-async xpc

在这里,我尝试在一秒钟内得到xpc答复。我不想阻止整个应用程序,因此我尝试在1秒后检查结果。但它总是在sleep(1)中崩溃。有谁知道这样做的最好方法是什么?

我尝试了sleep(1)std::this_thread::sleep_for(2s);dispatch_group_wait,但是没有运气。每当线程唤醒它崩溃时,以下是我调用xpc的代码,并在1秒后检索该值。

// send message
static int result = ETIME;
xpc_connection_send_message_with_reply(mConn, msg, NULL, ^(xpc_object_t reply){
    if (reply == XPC_ERROR_CONNECTION_INVALID || reply == XPC_ERROR_CONNECTION_INTERRUPTED) {
        result = ENOTCONN;
    }
    if (xpc_get_type(reply) != XPC_TYPE_DICTIONARY) {
        result = EINVAL;
    }
    result = (int)xpc_dictionary_get_int64(reply, sResult);
    xpc_release(reply);
    printf("leave\n");
});
// wait 1 second for result
//dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC);
std::this_thread::sleep_for(2s); // crash happened

1 个答案:

答案 0 :(得分:0)

经过大量研究后终于解决了该问题。要实现这一目标,最好的方法是让GCD进行以下工作,并且崩溃不是由睡眠引起的,实际上它是由xpc_release(reply);引起的,这应该在服务器端调用。您需要在REPLY MESSAGES部分的http://www.manpagez.com/man/3/xpc_connection_send_message_with_reply_sync/中查看更多详细信息。全部检查修复程序:

static int result = ETIME;
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
xpc_connection_send_message_with_reply(mConn, msg, NULL, ^(xpc_object_t reply){
    // reply will be release in server sige
    // so never call xpc_release(reply) here
    // or it will crash when it finish
    if (reply == XPC_ERROR_CONNECTION_INVALID || reply == XPC_ERROR_CONNECTION_INTERRUPTED) {
        result = ENOTCONN;
    }
    if (xpc_get_type(reply) != XPC_TYPE_DICTIONARY) {
        result = EINVAL;
    }
    result = (int)xpc_dictionary_get_int64(reply, sResult);
    // xpc_release(reply); !!! call this in server side or will crash here !!!
    dispatch_group_leave(group);
    printf("leave\n");
});
// wait 1 second for result
dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC);
dispatch_group_wait(group, timeout);
printf("end\n");