首页 > 解决方案 > 我无法在 C 中发送消息

问题描述

我正在编写这个脚本,以便练习在 c 中使用 mq_send() 和 mq_receive() 系统调用发送消息,但我被困在这里。我无法从这个简单的代码中获得任何输出。我试图定义 attr 结构,但没有任何改变。有人能帮我吗?

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <mqueue.h>
#include <sys/types.h>
#include <sys/wait.h>
#define Q "/queue"
#define SIZE 1024

int main(){
    mqd_t qd_w;
    mqd_t qd_r = mq_open(Q,O_CREAT|O_RDONLY, 0660, NULL);

    
    pid_t pid = fork();

    //son
    if(pid == 0){
        char str_w[] = "ciaoooo";
        //scanf("%s",str_w);
        qd_w = mq_open(Q, O_WRONLY, 0660, NULL);
        mq_send(qd_w, (const char*)str_w, strlen(str_w),0);
        mq_close(qd_w);
        exit(0);
    }else{

        //parent    
        wait(NULL);
        char* str_r = malloc(sizeof(char)*SIZE);
        mq_receive(qd_r, str_r, sizeof(char)*SIZE, NULL);
        printf("%s \n", str_r);
        mq_close(qd_r);
        mq_unlink(Q);

        return 0;
    }
}

标签: cmessagesystem-calls

解决方案


如果您打印出receive 的返回值,您会看到它在EMSGSIZE 上失败。

如果您查看手册页 ( https://man7.org/linux/man-pages/man3/mq_receive.3.html ),您将看到此错误的含义:

  EMSGSIZE
         msg_len was less than the mq_msgsize attribute of the
         message queue.

如果没有指定任何属性,消息队列的 mq_msgsize 是多少?您可以使用 来检查它mq_getattr,或者相信我的话它是 8K。

您使用的消息大小为 1024。尝试将其更改为 8192,您的代码将正常工作。

PS:正如评论中提到的人,你的代码还有其他问题——你不检查返回值,你没有在阅读消息后验证字符串 NULL 终止,你真的应该修复你的缩进。但这与您的问题无关,请记下。


推荐阅读