Linux ipc msgsnd() 失败
Linux ipc msgsnd() fails
我正在编写一个使用 unix 消息队列的程序。问题是这样的,程序报我"Error: 22: invalid arguments"。我已经 brpwsed,但它不能满足我的搜索。这是简单的代码:
bool msg::send(int key, void* data)
{
(void) data;
bool res = false;
m_msgId = msgget(key, m_mask);
if (m_msgId == -1) {
// noone create it
if ((m_msgId = msgget(key, m_mask | IPC_CREAT)) == -1) {
fprintf(stderr, "Error creating message: %d:(%s)\n",
errno,
strerror(errno));
return res;
}
}
union {
msg m;
char c[sizeof(msg)];
} u = {*this}; // it`s a deep copy
// here the program fails //
int ret = msgsnd(m_msgId, u.c,
sizeof(msg), IPC_NOWAIT);
if (ret == -1) {
if (errno != EAGAIN) {
// here is errno 22 //
fprintf(stderr, "Error creating message: %d:(%s)\n",
errno,
strerror(errno));
return res;
} else {
if (msgsnd(m_msgId, u.c,
sizeof(msg), 0) == -1) {
fprintf(stderr, "Error creating message: %d:(%s)\n",
errno,
strerror(errno));
res = false;
}
}
}
res = true;
return res;
}
如果我尝试发送像“1234567”这样的普通字符串,没问题。但是这个缓冲区发送失败。我做错了什么?
谢谢
msgsnd
的一个 EINVAL 条件是 "the value of mtype is less than 1"。
msgsnd
期望发送缓冲区是 long 描述消息类型 (mtype),后跟消息本身。您错误地没有设置消息类型,因此 msgsnd
会将消息的前 long 长度字节解释为 mtype .当消息为 "1234567"
但因 *this
.
而失败时,这恰好有效
你想定义这样的东西:
struct mymsg {
long mtype;
char mtext[SUFFICIENTLY_LARGE];
};
并在显式设置 mtype >= 1.
的同时将您的消息复制到 mtext 中的内存
我正在编写一个使用 unix 消息队列的程序。问题是这样的,程序报我"Error: 22: invalid arguments"。我已经 brpwsed,但它不能满足我的搜索。这是简单的代码:
bool msg::send(int key, void* data)
{
(void) data;
bool res = false;
m_msgId = msgget(key, m_mask);
if (m_msgId == -1) {
// noone create it
if ((m_msgId = msgget(key, m_mask | IPC_CREAT)) == -1) {
fprintf(stderr, "Error creating message: %d:(%s)\n",
errno,
strerror(errno));
return res;
}
}
union {
msg m;
char c[sizeof(msg)];
} u = {*this}; // it`s a deep copy
// here the program fails //
int ret = msgsnd(m_msgId, u.c,
sizeof(msg), IPC_NOWAIT);
if (ret == -1) {
if (errno != EAGAIN) {
// here is errno 22 //
fprintf(stderr, "Error creating message: %d:(%s)\n",
errno,
strerror(errno));
return res;
} else {
if (msgsnd(m_msgId, u.c,
sizeof(msg), 0) == -1) {
fprintf(stderr, "Error creating message: %d:(%s)\n",
errno,
strerror(errno));
res = false;
}
}
}
res = true;
return res;
}
如果我尝试发送像“1234567”这样的普通字符串,没问题。但是这个缓冲区发送失败。我做错了什么? 谢谢
msgsnd
的一个 EINVAL 条件是 "the value of mtype is less than 1"。
msgsnd
期望发送缓冲区是 long 描述消息类型 (mtype),后跟消息本身。您错误地没有设置消息类型,因此 msgsnd
会将消息的前 long 长度字节解释为 mtype .当消息为 "1234567"
但因 *this
.
你想定义这样的东西:
struct mymsg {
long mtype;
char mtext[SUFFICIENTLY_LARGE];
};
并在显式设置 mtype >= 1.
的同时将您的消息复制到 mtext 中的内存