消息队列提供了从一个进程向另外一个进程发送一块数据的方法,每个数据块认为有一个类型(通俗说法是一个通道),但是接受通道与发送通道必须一致才能实现通信。消息队列的不足之处在于每个消息最大长度有限度,每个消息队列总字节数有限制,系统的消息队列有限制。
命令:
cat /proc/sys/kernel/msgmax :查看一条信息最大有多大
cat /proc/sys/kernel/msgmnb :查看消息队列中信息最大有多大
cat /proc/sys/kernel/msgmni :查看系统中消息队列最大有多大
命令 ipcs -q :查看消息队列
命令 ipcrm -Q 消息队列名:删除消息队列
任务:创建一个消息队列、往消息队列中发数据、在消息队列中取数据、删除消息队列(在内核中删除这个对象)
(1)创建一个消息队列:
- int main()
- 8 {
- 9 int id=msgget(1234,IPC_CREAT|0644);//创建一个消息队列,名字为1234
- 10 if(id==-1)
- 11 {
- 12 perror("msgget failure\n");
- 13 exit(0);
- 14 }
- 15 printf("creat is ok\n");
- 16 return 0;
- 17
- 18 }
(2)往消息队列中发数据
- 3 #include <stdlib.h>
- 4 #include <fcntl.h>
- 5 #include <sys/ipc.h>
- 6 #include <sys/msg.h>
- 7 #include <string.h>
- 8
- 9 //消息队列发送数据的要求,以一个结构体
- 10 struct mybuf
- 11 {
- 12 long channel;//通道号
- 13 char mtext[100];//一块缓冲区,装发送数据
- 14 };
- 15
- 16 int main()
- 17 {
- 18 //打开之前创建的消息队列
- 19 int id=msgget(1234,0);
- 20 if(id==-1)
- 21 {
- 22 perror("msgget failure\n");
- 23 exit(1);
- 24 }
- 25
- 26 struct mybuf buf;//内存中创建一个待发送数据结构体
- 27
- 28 while(1)
- 29 {
- 30 printf("您要输入的通道号channel:");
- 31 scanf("%d",&buf.channel);//将输入的通道号,放入结构体对应通道号的位置
- 32
- 33 printf("您要往此通道输入的内容mtext:");
- 34 scanf("%s",buf.mtext);//将输入的内容,放在结构体对应存放主体内容的位置
- 35
- 36 //将buf里面的数据发送到id这个消息队列
- 37 if(msgsnd(id,&buf,strlen(buf.mtext),0)==-1)
- 38 {
- 39 perror("snd failure\n");
- 40 exit(1);
- 41 }
- 42 printf("send is ok\n");
- 43 }
(3)在消息队列中取数据
- 3 #include <stdio.h>
- 4 #include <stdlib.h>
- 5 #include <fcntl.h>
- 6 #include <sys/ipc.h>
- 7 #include <sys/msg.h>
- 8 #include <string.h>
- 9
- 10 //消息队列发送数据的要求,以一个结构体
- 11 struct mybuf
- 12 {
- 13 long channel;//通道号
- 14 char mtext[100];//一块缓冲区,装发送数据
- 15 };
- 16
- 17 int main()
- 18 {
- 19 //打开之前创建的消息队列
- 20 int id=msgget(1234,0);
- 21 if(id==-1)
- 22 {
- 23 perror("msgget failure\n");
- 24 exit(1);
- 25 }
- 26
- 27 struct mybuf buf;//内存中创建一个待发送数据结构体
- 28
- 29 while(1)
- 30 {
- 31 int channel=0;
- 32 printf("请输入您要读取通道号:");
- 33 scanf("%d",&channel);
- 34 memset(&buf, 0x00, sizeof(buf));
- 35 msgrcv(id,&buf,100,channel,0);
- 36 printf("buf.mtext=%s\n",buf.mtext);
- 37 }
- 38 return 0;
- 39 }
(4)删除消息队列(在内核中删除这个对象)
int msgctl(int msqid, int cmd, struct msqid_ds *buf)
Msgctl为创建消息队列返回的消息队列标识符
Cmd为命令,当执行删除消息队列时,就用IPC_RMID
Buf也是当执行删除时,就用0