消息队列

unix早期通信机制之一的信号能够传送的信息量有限,管道则只能传送无格式的字节流,这无疑会给应用程序开发带来不便。消息队列(也叫做报文队列)则克服了这些缺点。

消息队列就是一个消息的链表.可以把消息看作一个记录,具有特定的格式.进程可以向中按照一定的规则添加新消息;另一些进程则可以从消息队列中读走消息

目前主要有两种类型的消息队列:

POSIX消息队列以及系统V消息队列,系统V消息队列目前被大量使用

系统V消息队列是随内核持续的,只有在内核重起或者人工删除时,该消息队列才会被删除

消息队列的内核持续性要求每个消息队列都在系统范围内对应唯一的键值,所以,要获得一个消息队列的描述字,必须提供该消息队列的键值

IPC_CREAT:

创建新的消息队列

IPC_EXCL:

与IPC_CREAT一同使用,表示如果要创建的消息队列已经存在,则返回错误。

IPC_NOWAIT:

读写消息队列要求无法得到满足时,不阻塞


发送

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define MSGKEY   1234

struct msgbuf
{
    long mtype;
    char mtext[100];
};

int main()
{
    int msgid,ret;
    struct msgbuf buf;
    msgid=msgget(MSGKEY,IPC_CREAT|IPC_EXCL);
    if(-1==msgid)
    {
        perror("msgget");
        exit(1);
    }
    while(1)
    {
        memset(&buf,0,sizeof(buf));
        scanf("%s",buf.mtext);
        buf.mtype=1;
        ret=msgsnd(msgid,&buf,sizeof(buf)-sizeof(long),0);
        if(-1==ret)
        {
            perror("msgsnd");
            exit(1);
        }
        if(!strncmp("bye",buf.mtext,3))
        {
            break;
        }

    }
    msgctl(msgid,IPC_RMID,NULL);
    return 0;
}

接收

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define MSGKEY   1234

struct msgbuf
{
    long mtype;
    char mtext[100];
};

int main()
{
    int msgid,ret;
    struct msgbuf buf;
    msgid=msgget(MSGKEY,0);
    if(-1==msgid)
    {
        perror("msgget");
        exit(1);
    }
    while(1)
    {
        memset(&buf,0,sizeof(buf));
        ret=msgrcv(msgid,&buf,sizeof(buf.mtext),1,0);
        if(-1==ret)
        {
            perror("msgrcv");
            exit(1);
        }
        if(!strncmp("bye",buf.mtext,3))
        {
            break;
        }
        printf("Receive From Message: %s\n",buf.mtext);

    }

    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值