一、消息队列
消息队列是一种链式队列。
Msqid_ds
:维护消息队列的结构体,队列的第一个消息指针msg_first
,最后一个消息指针msg_last
,消息中有一个成员指针next
。
每一个消息中包含有哪些内容:
Data 数据
Length 数据的长度
Type 数据的类型
消息的接收端可以根据消息的类型来接收。
例如:
1----voltage data
2----电流数据
3----有功功率
二、消息队列函数
1、msgget
例子:
#include "sys/types.h"
#include "sys/msg.h"
#include "signal.h"
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{
int msgid;
msgid = msgget(IPC_PRIVATE, 0777);
if(msgid < 0)
{
printf("create message queue failure\n");
return -1;
}
printf("create message queue success msgid = %d\n", msgid);
system("ipcs -q");
return 0;
}
2、msgctl
例子:
#include "sys/types.h"
#include "sys/msg.h"
#include "signal.h"
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{
int msgid;
msgid = msgget(IPC_PRIVATE, 0777);
if(msgid < 0)
{
printf("create message queue failure\n");
return -1;
}
printf("create message queue success msgid = %d\n", msgid);
system("ipcs -q");
// delete message queue
msgctl(msgid, IPC_RMID, NULL);
system("ipcs -q");
return 0;
}
3、msgsnd
例子:
#include "sys/types.h"
#include "sys/msg.h"
#include "signal.h"
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
struct msgbuf
{
long type;
char voltage[124];
char ID[4];
};
int main()
{
int msgid;
struct msgbuf sendbuf;
msgid = msgget(IPC_PRIVATE, 0777);
if(msgid < 0)
{
printf("create message queue failure\n");
return -1;
}
printf("create message queue success msgid = %d\n", msgid);
system("ipcs -q");
// init sendbuf
sendbuf.type = 100;
printf("please input message:\n");
fgets(sendbuf.voltage, 124, stdin); // 从键盘敲入124个
// start write message to message queue
msgsnd(msgid, (void *)&sendbuf, strlen(sendbuf.voltage), 0);
while(1); // 加上循环看看有没有写进去
// delete message queue
msgctl(msgid, IPC_RMID, NULL);
system("ipcs -q");
return 0;
}
4、msgrcv
消息队列中数据读后,数据也不存在了。
#include "sys/types.h"
#include "sys/msg.h"
#include "signal.h"
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
struct msgbuf
{
long type;
char voltage[124];
char ID[4];
};
int main()
{
int msgid;
struct msgbuf sendbuf, recvbuf;
int readret;
msgid = msgget(IPC_PRIVATE, 0777);
if(msgid < 0)
{
printf("create message queue failure\n");
return -1;
}
printf("create message queue success msgid = %d\n", msgid);
system("ipcs -q");
// init sendbuf
sendbuf.type = 100;
printf("please input message:\n");
fgets(sendbuf.voltage, 124, stdin); // 从键盘敲入124个
// start write message to message queue
msgsnd(msgid, (void *)&sendbuf, strlen(sendbuf.voltage), 0);
// start read message from message queue
memset(recvbuf.voltage, 0 ,124); //先清空缓存
readret = msgrcv(msgid, (void *)&recvbuf, 124, 100, 0);
printf("recv: %s", recvbuf.voltage);
printf("readret = %d\n", readret);
// delete message queue
msgctl(msgid, IPC_RMID, NULL);
system("ipcs -q");
return 0;
}