消息队列本质上就是一个消息的链表,进程间可通过发送消息和接收消息来进行数据通讯。以下是我个人实现的消息队列,可供参考。
工具/原料
方法/步骤
1使用步骤: 1)创建:key_t key=ftok(PATH,proj); int msgid=msgget(key,IPC_CREAT | 0600) 2)发送:msgsnd(msgid,&msg,strlen(msg.mtext),0) 3)接收:msgrcv(msgid,&msg,strlen(msg.mtext),msg.mtype,0) 4)回收:msgctl(msgid,IPC_RMID,NULL)
2实现读消息的代码:#include #include #include #include #include #include #include #define TXT_SIZE 100 struct msgbuf{ long type; char txt[TXT_SIZE];}; int main(){ key_t key; //生成KEY key=ftok('/home/lbh',10); int msgid; if(-1 == (msgid=msgget(key,IPC_CREAT | 0660)))//创建消息队列 { perror('msgget'); exit(-1); } struct msgbuf msg; bzero(&msg,sizeof(msg)); msgrcv(msgid,&msg,sizeof(msg.txt),1,0);//接收消息 printf('I get msg:%s\n',msg.txt); return 0;}
3实现写消息的代码:#include #include #include #include #include #include #include #define TXT_SIZE 100 struct msgbuf{ long type; char txt[TXT_SIZE];}; int main(){ key_t key; //生成KEY key=ftok('/home/lbh',10); int msgid; if(-1 == (msgid=msgget(key,IPC_CREAT | 0660)))//创建 { perror('msgget'); exit(-1); } struct msgbuf msg; bzero(&msg,sizeof(msg)); msg.type=1; strcpy(msg.txt,'hello'); msgsnd(msgid,&msg,strlen(msg.txt),0);//发送消息 return 0;}
4在终端窗口中使用命令“gcc msgq_read.c -o read”和 “gcc msgq_write.c -o write”编译,使用命令“./read”和“./write”执行,效果如下:
注意事项
1使用消息队列时,需要用户自定义一个表示消息的结构体,要求该结构体具有以下成员:struct MSG { long mtype; char mtext[SIZE]; };
2使用消息队列的优点:不存在同步问题;缺点:容量太小,系统中只允许同时存在16条消息队列;每条消息队列的最大容量为16KB;消息的最大容量为8KB。