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

标签 c linux ipc message-queue

我正在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/

相关文章:

c - 使用 FFI 的带有 size_t 的 printf

iphone - 在 iPhone SDK 中集成 C 项目

c - 错误 'struct ec_key_st' 类型的定义不完整,使用 OpenSSL

c - 没有类型声明的linux内核代码不是注释,这是什么意思?

linux - 为什么 ((counter++)) 在 counter == 0 时失败?

c - 不是如何一起使用 header 和指针

linux - 使用linux命令在txt文件中设置范围

Windows 上的 JAVA IPC

ios - 一个应用程序如何在不切换应用程序的情况下向另一个应用程序提供数据?

c++ - boost::interprocess 锁持久性