gpt4 book ai didi

C++ mq_receive EMSGSIZE问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:57:46 24 4
gpt4 key购买 nike

我正在尝试使用 mqueue 发送消息“test”,但是消息接收失败并显示 EMSGSIZE。代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <mqueue.h>
#include <errno.h>

using namespace std;

int main() {
mqd_t mqdes;
mqdes = mq_open("/mq.12345", O_RDWR | O_CREAT, (S_IRWXU | S_IRWXG | S_IRWXO), NULL);

if (mqdes == -1) {
switch (errno) {
case EACCES:
cout << "EACCESS" << endl;
break;
case EEXIST:
cout << "EEXIST" << endl;
break;
case EINTR:
cout << "EINTR" << endl;
break;
case EINVAL:
cout << "EINVAL" << endl;
break;
case EMFILE:
cout << "EMFILE" << endl;
break;
case ENAMETOOLONG:
cout << "TOOLONG" << endl;
break;
case ENFILE:
cout << "ENFILE" << endl;
break;
case ENOENT:
cout << "ENOENT" << endl;
break;
case ENOSPC:
cout << "ENOSPC" << endl;
break;
}
} else {
cout << "Success" << endl;
}

pid_t pid;
pid = fork();
if (pid > 0) {
// Child process
string serialized = "test";
if (mq_send(mqdes, serialized.c_str(), strlen(serialized.c_str()), 0) != 0){
switch (errno) {
case EAGAIN:
cout << "EAGAIN" << endl;
break;
case EBADF:
cout << "EBADF" << endl;
break;
case EINTR:
cout << "EINTR" << endl;
break;
case EINVAL:
cout << "EINVAL" << endl;
break;
case EMSGSIZE:
cout << "EMSGSIZAE" << endl;
break;
case ENOSYS:
cout << "ENOSYS" << endl;
break;
}
} else {
cout << "Sent" << endl;
}

exit(1);
} else {
// Parent process
}

int status;
while (wait(&status) > 0) {
}

ssize_t size;
char* buf;
cout << mq_receive(mqdes, buf, 8, NULL) << endl;

switch (errno) {
case EAGAIN:
cout << "EAGAIN" << endl;
break;
case EBADF:
cout << "EBADF" << endl;
break;
case EMSGSIZE:
cout << "EMSGSIZAE" << endl;
break;
case EINTR:
cout << "EINTR" << endl;
break;
case ENOSYS:
cout << "ENOSYS" << endl;
break;
}

return 0;
}

接收时打印 -1 和 EMSGSIZE errno。怎么了?

编辑:我正在使用 Fedora 15

最佳答案

来自mq_receive page

[EMSGSIZE]指定的消息缓冲区大小msg_len小于消息队列的消息大小属性。

很可能消息缓冲区太小而无法包含完整的消息。

char* buf;
cout << mq_receive(mqdes, buf, 8, NULL) << endl;

应该是这样的

char buf[1024];
cout << mq_receive(mqdes, buf, 1024, NULL) << endl;

将 default: 放在 switch case 中也是一个很好的做法。

关于C++ mq_receive EMSGSIZE问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7338338/

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