【发布时间】: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