【问题标题】:Want to Receive dynamic length data from a message queue in IPC?想要从 IPC 中的消息队列接收动态长度数据?
【发布时间】:2012-06-26 12:53:57
【问题描述】:

这里我必须使用 SysV 消息队列发送和接收动态数据。

所以在结构字段中我有动态内存分配char *,因为它的大小可能会有所不同。

那么我怎样才能在接收方接收这种类型的消息。

请告诉我如何使用消息队列发送动态长度的数据。

我遇到了问题,我在下面发布了我的代码。

send.c

/*filename   : send.c
 *To compile : gcc send.c -o send
 */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct my_msgbuf {
    long mtype;
    char *mtext;
};

int main(void)
{
    struct my_msgbuf buf;
    int msqid;
    key_t key;
    static int count = 0;
    char temp[5];
    int run = 1;
    if ((key = ftok("send.c", 'B')) == -1) {
        perror("ftok");
        exit(1);
    }

    printf("send.c Key is = %d\n",key);

    if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) {
        perror("msgget");
        exit(1);
    }

    printf("Enter lines of text, ^D to quit:\n");

    buf.mtype = 1; /* we don't really care in this case */
    int ret = -1;
    while(run) {
        count++;
        buf.mtext = malloc(50);
        strcpy(buf.mtext,"Hi hello test message here");
        snprintf(temp, sizeof (temp), "%d",count);
        strcat(buf.mtext,temp);
        int len = strlen(buf.mtext);
        /* ditch newline at end, if it exists */
        if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0';
        if (msgsnd(msqid, &buf, len+1, IPC_NOWAIT) == -1) /* +1 for '\0' */
        perror("msgsnd");
        if(count == 100)
            run = 0;
        usleep(1000000);
    }

    if (msgctl(msqid, IPC_RMID, NULL) == -1) {
        perror("msgctl");
        exit(1);
    }

    return 0;
}

receive.c

/* filename   : receive.c
 * To compile : gcc receive.c -o receive
 */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

struct my_msgbuf {
    long mtype;
    char *mtext;
};

int main(void)
{
    struct my_msgbuf buf;
    int msqid;
    key_t key;

    if ((key = ftok("send.c", 'B')) == -1) {  /* same key as send.c */
        perror("ftok");
        exit(1);
    }

    if ((msqid = msgget(key, 0644)) == -1) { /* connect to the queue */
        perror("msgget");
        exit(1);
    }

    printf("test: ready to receive messages, captain.\n");

    for(;;) { /* receive never quits! */
        buf.mtext = malloc(50);
        if (msgrcv(msqid, &buf, 50, 0, 0) == -1) {
            perror("msgrcv");
            exit(1);
        }
        printf("test: \"%s\"\n", buf.mtext);
    }

    return 0;
}

【问题讨论】:

  • 你为什么使用strcpysnprintfstrcat?为什么不直接使用snprintf

标签: c ipc message-queue


【解决方案1】:

解决问题的几种方法是:

  1. 使消息长度固定。
  2. 发送包含消息长度的固定长度“标头”。
  3. 发送终止符,因为您发送的字符串似乎包含终止符'\0'

编辑:如何使用msgsndmsgrcv

您对结构和msgsnd 的使用是错误的,因为该函数期望整个消息是一个连续的内存区域。诸如this 之类的示例使用其中包含普通字段的结构,或者诸如this(在底部)使用固定长度的字符串数组。

您也可以发送结构大小为动态的动态数据。这里的诀窍是使用一个固定大小的小型结构,并分配比需要更多的数据。

让我们重写部分示例发件人代码:

struct my_msgbuf {
    long   mtype;     /* Message type, must be > 0 */
    char   mtext[1];  /* Some compilers allow `char mtext[0]` */
};

/* ... */


int count = 0;
while (count < 100) {
    count++;

    /* Put string in a temporary place */
    char tmp[64];
    snprintf(tmp, sizeof(tmp), "Hi hello test message here %d", count);

    /* +1 for the terminating '\0' */
    size_t msgsz = strlen(tmp) + 1;

    /* Allocate structure, and memory for the string, in one go */
    struct my_msgbuf *buf = malloc(sizeof(struct my_msgbuf) + msgsz);

    /* Set up the message structure */
    buf->mtype = 1;
    memcpy(buf->mtext, tmp, msgsz);

    /* And send the message */
    msgsnd(msgid, buf, msgsz, IPC_NOWAIT);

    /* Remember to free the allocated memory */
    free(buf);
}

上面的代码处理动态字符串的发送,只要少于 63 个字符(临时字符串的大小减一)。

不幸的是msgrcv 并不真正支持接收动态大小的数据。这可以通过不使用MSG_NOERROR 标志来解决,检查错误E2BIG,然后使用realloc 来获得更大的消息缓冲区。

类似这样的接收:

/* Should start with larger allocation, using small just for example */
size_t msgsz = 8;
struct my_msgbuf *buf = NULL;

for (;;) {
    /* Allocate if `buf`  is NULL, otherwise reallocate */
    buf = realloc(buf, msgsz);

    /* Receive message */
    ssize_t rsz = msgrcv(msgid, buf, msgsz, 1, 0);

    if (rsz == -1) {
        if (errno == E2BIG)
            msgsz += 8;  /* Increase size to reallocate and try again */
        else {
            perror("msgrcv");
            break;
        }
    } else {
        /* Can use `buf->mtext` as a string, as it already is zero-terminated */
        printf("Received message of length %d bytes: \"%s\""\n", rsz, buf->mtext);
        break;
    }
}

if (buf != NULL)
    free(buf);

上面的接收代码只接收一条消息。如果你想让它匹配发送大量消息的发送者,那么将接收代码放在一个函数中,并在循环中调用它。

免责声明:此代码直接在浏览器中编写,仅阅读手册页。我没有测试过。

【讨论】:

  • 如何确定消息的固定长度?我想让它动态化。可能是receive.c 文件中的问题。你能给我推荐一些示例吗?
  • @user1089679 编辑了我的答案以包含一些关于如何处理动态消息的代码。
  • 发件人代码中的这个 mlen 怎么样,我认为 mlen = strlen(tmp)。我说的对吗?
  • @user1089679 啊,应该是msgsz
  • 感谢您的回答。我会把这个概念放在我的要求中,如果我会遇到任何问题,请告诉你。
猜你喜欢
  • 2010-11-13
  • 1970-01-01
  • 2014-05-03
  • 2012-11-16
  • 2012-09-19
  • 2021-03-12
  • 2014-05-04
  • 2020-11-21
  • 1970-01-01
相关资源
最近更新 更多