消息队列

来源:互联网 发布:中小企业 云计算 编辑:程序博客网 时间:2024/06/06 05:12
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   1234struct 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   1234struct 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;}



原创粉丝点击