gpt4 book ai didi

c - 消息队列(IPC)接收进程不打印C中接收到的数据

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

我正在C linux 中实现IPC 的消息队列机制。下面是我的接收过程。它不打印收到的消息。我认为它正在生成一个有效的 msqid,并且 msgrcv 函数的其他参数也是正确的。为什么会这样?

//header files
#include"msgbuf.h"
int main()
{
int msqid;
key_t key;
int msgflg = 0666;
message_buf *rbuf;
rbuf=malloc(sizeof(*rbuf));
rbuf->m=malloc(sizeof(M1));
key = ftok("/home/user",12);
if ((msqid = msgget(key, msgflg)) ==-1)
{
perror("msgget");
exit(1);
}
printf("\n\n%d\n",msqid); //working fine till here.
/* Receive an answer of message type 1. */
if (msgrcv(msqid, &rbuf, sizeof(rbuf->m), 1, 0) < 0)
{
perror("msgrcv");
exit(1);
}
/* Print the answer. */
printf("Received message text= %s\n", rbuf->m->cp);
return 0;
}

现在msgbuf.h

typedef struct msgclient
{
int msglen;
int msgtype;
char *cp;
}M1;


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

最佳答案

由于两个单独的进程有两个单独的内存区域,因此将指针传递给另一个进程是没有意义的,因为传递的指针如果指向接收进程中的任何内容,则不会指向它所在的任何内容指向原始进程。

您需要将 M1 中的 char *cp; 更改为字符数组,并在发送消息缓冲区之前将字符串复制到其中。指示字符串长度的长度字节可能也是可取的(但不一定是必需的)。

关于c - 消息队列(IPC)接收进程不打印C中接收到的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22631997/

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