【问题标题】:POSIX message queue linuxPOSIX消息队列linux
【发布时间】:2019-03-17 08:14:42
【问题描述】:

我正在尝试从发送方 mq_sender() 接收 mq_receive() 数据,当我使用先运行发送文件时它可以工作.. 但是如果我先运行接收,即使在将数据发送到队列之后它也会阻塞..我在下面附上了我的代码

    //sender
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<mqueue.h>
#include<string.h>
#include<unistd.h>
#define NAME "/queone"
#define MAX_SIZE 1021
void main()
{
        int i;
        struct mq_attr attr;
        attr.mq_maxmsg = 10;
        attr.mq_msgsize = MAX_SIZE;
        int fd;
        char s[MAX_SIZE]="hello";
        int r1,r2;


                mq_unlink(NAME);
                perror("mq_unlink");
                fd=mq_open(NAME,O_CREAT | O_WRONLY ,0664,&attr);
                printf("fd=%d\n",fd);
                for(i=0;i<5;i++)
                r1=mq_send(fd,s,sizeof(s),0);
                printf("%d",r1);
}
//receiver
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<mqueue.h>
#include<string.h>
#include<unistd.h>
#define NAME "/queone"
#define MAX_SIZE 1021
void main()
{
        struct mq_attr attr;
        attr.mq_maxmsg = 10;
        attr.mq_msgsize = MAX_SIZE;

        int fd,fd1,r;
        char s[MAX_SIZE];
                fd=mq_open(NAME,O_CREAT|O_RDONLY ,0664,&attr);
                perror("mq_open");
                printf("fd=%d\n",fd);
                mq_getattr(fd,&attr);
                printf("%d\n",attr.mq_curmsgs);
                printf("%d\n",attr.mq_msgsize);

                r=mq_receive(fd,s,sizeof(s),0);
                printf("%d",r);
                if(r==-1)
                perror("mq_receive");
                printf("%s\n",s);
                mq_unlink(NAME);


        }

如何处理

【问题讨论】:

    标签: linux posix message-queue


    【解决方案1】:

    问题是你在发件人中无条件调用mq_unlink。原因如下:

    1. 接收方创建消息队列
    2. 接收者在上面监听消息
    3. 接收器进入睡眠状态
    4. 发送方删除消息队列
    5. 发送者创建一个新的同名消息队列
    6. 发送者向新的消息队列发送消息

    由于发送方将消息发送到的消息队列不是接收方正在监听的队列,因此接收方显然没有收到消息。

    【讨论】:

      猜你喜欢
      • 2013-04-16
      • 2016-11-26
      • 2020-11-27
      • 1970-01-01
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      • 2015-04-12
      相关资源
      最近更新 更多