消息队列
消息队列,Unix的通信机制之一,可以理解为是一个存放消息(数据)容器。将消息写入消息队列,然后再从消息队列中取消息,一般来说是先进先出的顺序。可以解决两个进程的读写速度不同(处理数据速度不同),系统耦合等问题,而且消息队列里的消息哪怕进程崩溃了也不会消失。
相关函数:
1.msgget:创建一个新的或打开一个已经存在的消息队列
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgget(key_t key, int msgflg);
参数:
key:函数ftok的返回值或IPC_PRIVATE。
msgflag: IPC_CREAT:创建新的消息队列。
IPC_EXCL:与IPC_CREAT一同使用,表示如果要创建的消息队列已经存在,则返回错误。 IPC_NOWAIT:读写消息队列要求无法满足时,不阻塞。返回值: 调用成功返回队列标识符,否则返回-1
2.msgsnd:将一个新的消息写入队列
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
成功执行时,msgsnd()返回0
失败返回-1
3.msgrcv:从消息队列中读取消息
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
成功执行时,msgrcv()返回拷贝到mtext数组的实际字节数。
失败返回-1
接收端程序
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[128]; /* message data */
};
int main()
{
struct msgbuf readbuf;
int msgid=msgget(0x12345,IPC_CREAT|0777);
if(msgid==-1){
printf("get queue failed\n");
}
msgrcv(msgid,&readbuf,sizeof(readbuf.mtext),888,0);
printf("read form que:%s\n",readbuf.mtext);
struct msgbuf sendbuf={988,"thank you"};
msgsnd(msgid,&sendbuf,sizeof(sendbuf.mtext),0);
return 0;
}
发送端程序
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[128]; /* message data */
};
int main()
{
struct msgbuf sendbuf={888,"this is message from queue"};
struct msgbuf readbuf;
int msgid=msgget(0x12345,IPC_CREAT|0777);
if(msgid==-1){
printf("get queue failed\n");
}
msgsnd(msgid,&sendbuf,strlen(sendbuf.mtext),0);
printf("send over\n");
msgrcv(msgid,&readbuf,sizeof(readbuf.mtext),988,0);
printf("return from get:%s\n",readbuf.mtext);
return 0;
}