c - 我无法在 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;
}
}
解决方案
如果您打印出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 终止,你真的应该修复你的缩进。但这与您的问题无关,请记下。
推荐阅读
- laravel - 机器对机器的 Nuxt 和 laravel 护照 api
- c# - .Net Oracle.ManagedDataAccess 异常处理(ORA-00001:违反唯一约束 (x))
- logging - 如何在日志记录中设置 VM 输出警报
- monetdb - MonetDB 上的集群配置:无法发现其他节点
- azure-maps - 如何显示天蓝色地图路线方向
- verilog - SystemVerilog Generate 支持延迟吗?
- ios - 通过一个简单的例子解释我在 Swift 中的委托
- sql - 在 WHERE NOT EXISTS 之后加入
- java - 如何从 ListView 中删除一个项目并在 Firebase 上删除它?
- html - 为什么“字体粗细”适用于“选择”元素的选定“选项”,而“颜色”不适用?