繁体   English   中英

消息队列(IPC)接收过程未在C中打印接收到的数据

[英]message queue(IPC) receiving process not printing the received data in C

我正在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;
if (msgrcv(msqid, &rbuf, sizeof(rbuf->m), 1, 0) < 0)

应该

if (msgrcv(msqid, &rbuf, sizeof(struct message_buf), 1, 0) < 0)

由于两个单独的进程具有两个单独的内存区域,因此没有必要将指针传递给另一个进程,因为传递的指针(如果它在接收进程中根本指向任何东西)将不会指向它所指向的内容。原始过程。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM