gpt4 book ai didi

c - msgrcv() 中的错误 :receiving data through message queue in C

转载 作者:行者123 更新时间:2023-11-30 17:36:34 30 4
gpt4 key购买 nike

我正在使用 C linux 中的消息队列机制发送消息。但是msgrcv函数有一些问题。它显示错误为无效参数。请检查这一点。

//msgrcv.c
#include"msgbuf.h"
int main()
{
int msqid;
key_t key;
message_buf *rbuf;
rbuf=malloc(sizeof(*rbuf));
// rbuf->m=malloc(sizeof(M1));

key = ftok("/home/user",'a');
if ((msqid = msgget(key, IPC_CREAT)) ==(key)-1)
{
perror("msgget");
exit(1);
}

/* Receive an answer of message type 1. */
if (msgrcv(msqid, &rbuf, sizeof(rbuf->m), 1, 0) < 0)
{
perror("msgrcv"); //invalid argument to msgrcv
exit(1);
}
/* Print the answer. */
printf("Received message text= %s\n", rbuf->m.cp);
return 0;
}

现在msgbuf.h

 //msgbuf.h
typedef struct msgclient
{
int msglen;
int msgtype;
char *cp;
}M1;

typedef struct msgbuf1
{
long mtype;
M1 m;
} message_buf;

我还想知道如何使用消息队列进行双向通信。我是否需要创建两个消息队列来完成两个进程之间的通信?也欢迎相同的示例代码。

谢谢:)

最佳答案

我猜是这个

if ((msqid = msgget(key, 0666)) ==key-1)

应该是

if ((msqid = msgget(key, 0666)) == -1)

来自msgrcv

ERRORS
The msgrcv() function will fail if:
...
[EINVAL]
msqid is not a valid message queue identifier.

此外,message_buf.m不能是指针,而是成员

typedef struct msgbuf1
{
long mtype;
M1 m;
} message_buf;

然后您可以将此调用保存到 malloc

rbuf->m=malloc(sizeof(M1));

msgrcv 的调用应该是

if (msgrcv(msqid, rbuf, sizeof(rbuf->m), 1, 0) < 0)

否则,msgrcv 将覆盖您的堆栈。

更新:

来自msgget

ERRORS
[ENOENT]
A message queue identifier does not exist for the argument key and (msgflg & IPC_CREAT) is 0.

这意味着,您必须调用

if ((msqid = msgget(key, IPC_CREAT | 0666)) == -1)

至少在您第一次调用此函数时是这样。

关于c - msgrcv() 中的错误 :receiving data through message queue in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22627307/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com