【问题标题】:UNIX message queue msgrcv failed to receive messageUNIX 消息队列 msgrcv 接收消息失败
【发布时间】:2011-07-15 03:51:30
【问题描述】:

亲爱的朋友们, 知道为什么 msgrcv 会收到空白缓冲区吗?

代码如下:

enter code here
 #include <sys/msg.h>
 #include <unistd.h>
 #include <sys/types.h>
 #include <stdio.h>
 #include <string.h>

 typedef struct mymsg {
  long mtype;
  char mtext[24];
 }mymsg;

 int main()
 {
  int msqid;
  mymsg msg,buff;
  msqid=msgget(IPC_PRIVATE,IPC_CREAT|IPC_EXCL);

  if(msqid==-1){
  perror("FAiled to create message queue\n");
  }
  else{
  printf("Message queue id:%u\n",msqid);
  }
  msg.mtype=1;
  strcpy(msg.mtext,"This is a message");
  if(msgsnd(msqid,&msg,sizeof(msg.mtext),0)==-1){
   perror("msgsnd failed:");
  }
  else{
   printf("Message sent successfully\n");
  }
 //ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg);

  // msgrcv(msqid,buff.mtext,sizeof(msg.mtext),1,0); This was error
  msgrcv(msqid,&buff,sizeof(msg.mtext),1,0);  // This is correct (Thanks to Erik)
  printf("The message received is: %s\n",buff.mtext);
 }

   Output:
   [root@dhcppc0 message_queue]# ./a.out
   Message queue id:294919
   Message sent successfully
   The message received is: 
                                                    1,1           Top

【问题讨论】:

    标签: c unix message-queue msgrcv


    【解决方案1】:

    msgbuf.mtype 必须设置为 1 - 因为您告诉 msgrcv 您需要类型 1 的消息。

    或者,您可以将msgbuf.mtype 设置为任何正值,然后通过将0 作为msgtyp 参数传递来告诉msgrcv 您需要任何消息类型。

    另外,msgrcv 需要一个指向 msgbuf 的指针:

    msgrcv(msqid,&buff,sizeof(msg.mtext),1,0);
    

    编辑:经过测试的工作源:

     #include <sys/msg.h>
     #include <unistd.h>
     #include <sys/types.h>
     #include <stdio.h>
     #include <string.h>
    
     typedef struct mymsg {
      long mtype;
      char mtext[24];
     }mymsg;
    
     int main()
     {
      int msqid;
      mymsg msg,buff;
      msqid=msgget(IPC_PRIVATE,IPC_CREAT|IPC_EXCL);
    
      if(msqid==-1){
      perror("FAiled to create message queue\n");
      }
      else{
      printf("Message queue id:%u\n",msqid);
      }
      msg.mtype=1; // was there failed to copy
      strcpy(msg.mtext,"This is a message");
      if(msgsnd(msqid,&msg,sizeof(msg.mtext),0)==-1){
       perror("msgsnd failed:");
      }
      else{
       printf("Message sent successfully\n");
      }
     //ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg);
    
      msgrcv(msqid,&buff,sizeof(msg.mtext),1,0);
      printf("The message received is: %s\n",buff.mtext);
     }
    

    【讨论】:

    • 对不起,那一行:msg.mtype=1;已经在那里了,我错过了复制它。但还是不行。
    • @kingsmasher1:更新答案
    • 对不起,请稍等。让我再编译一次。
    猜你喜欢
    • 2018-09-09
    • 2011-02-20
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 2010-09-19
    • 2014-05-02
    相关资源
    最近更新 更多