linux消息队列

来源:互联网 发布:人类进化史知乎 编辑:程序博客网 时间:2024/06/07 00:36
共享内存:
  双工 数据流 数据无边界 数据无序 保存最后一个数据

 消息队列,共享队列:本质还是共享内存
 消息队列中的消息是结构体。
 编程模型:
  A        B
 定义接收结构体  msgbuf  定义发送结构体
         制作msg
 创建key       创建key
 创建msgq  msgget 
 设置msgq   msgctl    
         获取msgq(msgget) 
 接收msg  msgrcv    发送msg msgsnd
 删除msgq    msgctl
 #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/msg.h>
    int msgget(//成功返回msgid失败返回-1
    key_t key,  //key
    int msgflg);//方式和权限
    int  msgctl(
    int  msqid,  //
    int   cmd,   //行为方式  IPC_RMID IPC_STAT IPC_SET
    struct msqid_ds *buf);//msg信息结构体

    struct msgbuf {
        long mtype;  /* message type, must be > 0 */
        char mtext[1];/* message data */
    };
    int msgsnd(
    int msqid, //msgget的返回值
    const void *msgp, //指向结构体的指针
    size_t msgsz, //结构体中mtext大小
    int msgflg); //发送方式
     MSG_NOWAIT   非阻塞方式
     0   默认方式 阻塞方式

    ssize_t msgrcv(
    int msqid,
    void *msgp,
    size_t msgsz,
    long msgtyp,//接收的信息类型
    int msgflg);

A

#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#include <stdlib.h>//每条消息的长度#define LEN 20struct msgbuf{//step1:制作消息结构体long mtype;char mtext[LEN];};int main(){//step2:制作keykey_t key = ftok(".",99);if(-1 == key) printf("ftok error:%m\n"),exit(-1);printf("ftok %m\n");//step3:创建msgqint msgid = msgget(key,IPC_CREAT|0666);if(-1 == msgid) printf("message quque creat error:%m\n"),exit(-1);printf("message quque creat %m\n");//step4:设置msgq大小//不需要设置大小,内核会自定义其大小这个程序中足够使用//step5:从msgq中接收消息int i;long type = 2;struct msgbuf buf;int r;for(i=0;i<10;i++){r = msgrcv(msgid,&buf,LEN,type,IPC_NOWAIT);if(r>0)printf(">> %s\n",buf.mtext);}}


B

#include <stdio.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#include <stdlib.h>#include <string.h>//每条消息的长度#define LEN 20struct msgbuf{//step1:制作消息结构体long mtype;char mtext[LEN];};int main(){//step2:制作keykey_t key = ftok(".",99);if(-1 == key) printf("ftok error:%m\n"),exit(-1);printf("ftok %m\n");//step3:创建msgqint msgid = msgget(key,0);if(-1 == msgid) printf("message quque creat error:%m\n"),exit(-1);printf("message quque creat %m\n");//step4:发送消息到msgq中int i;struct msgbuf buf[20];int r;//4.1 制作消息for(i=0;i<10;i++){sprintf(buf[i].mtext,"%s:%d","hello",i);buf[i].mtype = 1;}for(i=10;i<20;i++){sprintf(buf[i].mtext,"%s:%d","world",i);buf[i].mtype = 2;}//4.2 发送消息for(i=0;i<20;i++){r = msgsnd(msgid,&buf[i],LEN,IPC_NOWAIT);if(!r)printf("发送完第%d条消息!\n",i+1);elseprintf("send %d error:%m\n",i);}}


0 0
原创粉丝点击