1

我是 Linux C 和 C++ 编程的新手。我正在尝试为系统 v ipc 消息队列创建一个 C++ 类,但我遇到了 1 个问题。我为这样的消息写了类:

class message
{
    friend class queue;
private:
    typedef struct
    {
        long mtype;
    char mdata[maxmsg_buf];
    }msgbuf_t, *msgbuf_ptr_t;

    msgbuf_ptr_t msgbuf_ptr;
public:
    message(void):msgbuf_ptr(NULL)
    {
        msgbuf_ptr = new msgbuf_t;
    }
    ipc::message::message(const long& type, const std::string& data):msgbuf_ptr(NULL)
    {
    msgbuf_ptr = new msgbuf_t;

    msgbuf_ptr->mtype = type;
    if(data.length() <= maxmsg_buf)
    {
    strncpy(msgbuf_ptr->mdata, data.c_str(), data.length());
    }
    }
};

class queue
{
private:
    mutable qid_t qid;
public:
    queue(const key_t& qkey = unique, const perm_t& qperm = usr_rw, const flag_t& qflag = none)
    {
         qid = msgget(qkey, qperm | qflag);
    if(qid == -1)
    {
    throw errno;                //specify exception for queue  
    }
    }
    void send(const ipc::message& msg, const int& sflag) const
    {
    if((msgsnd(qid, &msg.msgbuf_ptr, sizeof(msg.msgbuf_ptr->mdata), sflag)) == -1)
    {
    throw errno;                //specify exception for queue 
    }
    }
};


//Usage:
ipc::queue q(0x0000FFFF, ipc::usr_rw, ipc::create);
ipc::message msg(10L, "First test message for sysVipc queue");

q.send(msg);   //throws EFAULT from here

当我将 msgbuf_ptr 发送到 msgsnd 系统调用时,它返回 EFAULT(Bad address) 错误。所以我的问题是:我可以使用 operator new 分配 msgbuf 吗?PS对不起,如果我的英语不好。

4

1 回答 1

1

问题出在您的 queue::send 方法中。 &msg.msgbuf_ptr是指向指针的指针。省略地址运算符&,你应该没问题。

编辑:没有等待 msg.msgbuf_ptr->mdata是你的消息。所以,你应该这样称呼它: msgsnd(qid, &msg.msgbuf_ptr + sizeof(msg.msgbuf.mtype), sizeof(msg.msgbuf_ptr->mdata), sflag)

于 2013-03-14T10:53:56.430 回答