我是 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对不起,如果我的英语不好。