1

我正在尝试设置一个 mach 消息,以便使用 mach IPC 发送一个字符串。但是,(ipc/send) invalid msg-header在尝试发送外线消息时出现错误。

这是消息结构。

struct ool_msg
{
    mach_msg_header_t header;
    mach_msg_body_t body;
    mach_msg_ool_descriptor_t data;
    mach_msg_type_number_t count;
};

我正在设置这样的标题。下面的变量msg是一个struct ool_msg

hdr = &(msg.header);
hdr->msgh_bits = MACH_MSGH_BITS_LOCAL(MACH_MSG_TYPE_COPY_SEND);
hdr->msgh_bits |= MACH_MSGH_BITS_COMPLEX;
hdr->msgh_size = sizeof(msg);
hdr->msgh_local_port = MACH_PORT_NULL;
hdr->msgh_remote_port = port;

这就是我设置 Mach 消息的其余部分的方式。

msg.body.msgh_descriptor_count = 1;
msg.data.address = string;
msg.data.size = strlen(string) + 1;
msg.data.deallocate = FALSE;
msg.data.copy = MACH_MSG_VIRTUAL_COPY;
msg.data.type = MACH_MSG_OOL_DESCRIPTOR;
msg.count = msg.data.size;

那么如何正确设置 OOL Mach IPC 的消息头呢?

编辑

这是一个重现我的问题的程序。

#include <stdio.h>
#include <mach/mach.h>

static char *string = "123456789";

struct ool_msg
{
    mach_msg_header_t header;
    mach_msg_body_t body;
    mach_msg_ool_descriptor_t data;
    mach_msg_type_number_t count;
};

int main(void)
{
    kern_return_t err;
    struct ool_msg msg;
    mach_msg_header_t *hdr;
    mach_port_t port = MACH_PORT_NULL;

    err = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't allocate mach port\n", err);
        return (-1);
    }

    err = mach_port_insert_right(mach_task_self(), port, port,
                                 MACH_MSG_TYPE_MAKE_SEND);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't insert port right\n", err);
        return (-1);
    }

    hdr = &(msg.header);
    hdr->msgh_bits = MACH_MSGH_BITS_LOCAL(MACH_MSG_TYPE_COPY_SEND);
    hdr->msgh_bits |= MACH_MSGH_BITS_COMPLEX;
    hdr->msgh_size = sizeof(msg);
    hdr->msgh_local_port = MACH_PORT_NULL;
    hdr->msgh_remote_port = port;

    msg.body.msgh_descriptor_count = 1;
    msg.data.address = string;
    msg.data.size = strlen(string) + 1;
    msg.data.deallocate = FALSE;
    msg.data.copy = MACH_MSG_VIRTUAL_COPY;
    msg.data.type = MACH_MSG_OOL_DESCRIPTOR;
    msg.count = msg.data.size;

    err = mach_msg(hdr,
                  MACH_SEND_MSG,
                  hdr->msgh_size,
                  0,
                  MACH_PORT_NULL,
                  MACH_MSG_TIMEOUT_NONE,
                  MACH_PORT_NULL);
    if(err != KERN_SUCCESS)
    {
        mach_error("Can't send mach msg\n", err);
        return (-1);
    }

    return (0);
}
4

1 回答 1

6

正如文档所述

MACH_MSGH_BITS_REMOTEMACH_MSGH_BITS_LOCAL宏返回适当的mach_msg_type_name_t值,给定一个msgh_bits值。给定两个值, 宏 MACH_MSGH_BITS为 构造一个值。msgh_bitsmach_msg_type_name_t

所以设置时需要使用MACH_MSGH_BITS宏而不是MACH_MSGH_BITS_LOCALmach_msg_header_t.msgh_bits。否则,您将其设置为 amach_msg_type_name_t而不是msgh_bits您想要的。

为了澄清,您需要类似以下代码来获取您的 msgh_bits:

hdr->msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND)
于 2016-03-13T22:55:36.557 回答