Очередь сообщения UNIX MSGRCV не удалось получить сообщение

StackOverflow https://stackoverflow.com/questions/5301467

  •  22-10-2019
  •  | 
  •  

Вопрос

Дорогие друзья, есть идея, почему 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
Это было полезно?

Решение

msgbuf.mtype Должен быть установлен на 1 - так как вы говорите msgrcv что вам нужны сообщения типа 1.

В качестве альтернативы вы можете установить msgbuf.mtype к любому положительному значению, а затем скажите msgrcv что вам нужен какой -либо тип сообщения, передав 0 как msgtyp аргумент

Также, 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);
 }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top