2

我正在尝试使用 mqueue 发送消息“测试”,但消息接收失败并出现 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

4

1 回答 1

2

mq_receive 页面

[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 案例中也是一个好习惯。

于 2011-09-07T20:49:56.260 回答