我用C编写了一个简单的程序,它使用IPC消息队列,但是当我将消息作为指针发送时,我无法接收它。#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <unistd.h>#include <error.h>#include <sys/types.h>#include <sys/wait.h>#include <sys/stat.h>#include <sys/ipc.h>#include <sys/msg.h>#include <ctype.h>#include <string.h>typedef struct Message { long type; char content[16];} Message;int main(int argc, char* argv[]) { printf("Starting...\n"); key_t key = 1; Message* msg = malloc(sizeof(Message)); int msg_id = msgget(key, IPC_CREAT | 0777); printf("ID of the created queue: %d\n", msg_id); strcpy(msg->content, "Hello"); msgsnd(msg_id, msg, 16, 0); free(msg); if (fork() == 0) { int msgid = msgget(key, 0); printf("Message queue id: %d\n", msgid); Message rcvMsg; msgrcv(msgid, &rcvMsg, 16, 0, 0); printf("Received: %s\n", rcvMsg.content); if (msgctl(msgid, IPC_RMID, 0) != 0) { perror("Cannot remove queue from system.\n"); exit(1); } exit(0); } wait(NULL); printf("Stop.\n"); exit(0);}我得到的结果是:Starting...ID of the created queue: 327680Message queue id: 327680程序正在等待。但当我以标准变量(而不是指向结构的指针)的形式发送消息时,消息就会被传递。工作程序:int main(int argc, char* argv[]) { printf("Starting...\n"); key_t key = 1; Message msg; int msg_id = msgget(key, IPC_CREAT | 0777); printf("ID of the created queue: %d\n", msg_id); strcpy(msg.content, "Hello"); msgsnd(msg_id, &msg, 16, 0); if (fork() == 0) { int msgid = msgget(key, 0); printf("Message queue id: %d\n", msgid); Message rcvMsg; msgrcv(msgid, &rcvMsg, 16, 0, 0); printf("Received: %s\n", rcvMsg.content); if (msgctl(msgid, IPC_RMID, 0) != 0) { perror("Cannot remove queue from system.\n"); exit(1); } exit(0); } wait(NULL); printf("Stop.\n"); exit(0);}此程序返回预期输出:Starting...ID of the created queue: 327680Message queue id: 327680Received: HelloStop.发生什么事?怎么了?如何调试?还有一个问题是,创建结构变量的最佳方法是什么-指针还是非指针(顺便问一下,结构的非指针变量的名称是什么?)是吗?Message msg;或Message* msg = malloc(sizeof(Message)); 最佳答案 您没有初始化消息的type字段。msgsnd要求类型字段具有正整数值。您应该更改代码,以便它使用返回值检查每个函数的返回值。我通过将msgsnd(msg_id, msg, 16, 0);更改为int result = msgsnd(msg_id, msg, 16, 0);发现了此错误,然后插入:if (result == -1){ perror("msgsnd"); exit(EXIT_FAILURE);}这告诉我msgsnd有一个无效的参数,所以我查看了它的文档,发现type必须是阳性的。您还应该检查msgrcv的返回值。对于像这样的小结构,不需要 >,除非您需要在创建它的函数之后继续存在该结构。如果函数只是要使用消息结构并丢弃它,请在本地声明它。如果函数要将消息结构返回给调用方,请使用malloc分配它并返回一个指针。(然后调用方负责稍后通过将其指针传递到malloc来释放它)关于c - C IPC-无法从队列接收消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48132737/
10-14 15:43
查看更多