【问题标题】:I can't manage to send messages in C我无法在 C 中发送消息
【发布时间】:2021-12-22 19:17:09
【问题描述】:

我正在编写这个脚本,以便练习在 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;
    }
}

【问题讨论】:

  • 第一步是检查所有系统调用的返回值。
  • 欢迎来到 SO。与接收无关,但这会导致未定义的行为:printf("%s \n", str_r); str_r 不是字符串,因为您不发送终止的 0 字节,也不要在接收后添加一个。
  • 您应该对代码应用适当的缩进以增加可读性。
  • 欢迎来到 SO。如果这是您的第一篇文章,请仔细阅读How do I ask a good question?

标签: c message system-calls


【解决方案1】:

如果您打印出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,您的代码将正常工作。

P.S:正如 cmets 中提到的那样,您的代码还有其他问题 - 您不检查返回值,您在阅读消息后不验证字符串 NULL 终止,您确实应该修复缩进。但这与您的问题无关,请记下。

【讨论】:

    猜你喜欢
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多