gpt4 book ai didi

c - Linux ipc msgsnd() 失败

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:58 29 4
gpt4 key购买 nike

我正在编写一个使用 unix 消息队列的程序。问题是这样的,程序报告我“错误:22:无效参数”。我已经 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 中的内存。

关于c - Linux ipc msgsnd() 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40047214/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com