一夫壁、消息隊列
消息隊列
消息隊列是一種鏈式隊列三椿。
Msqid_ds
:維護消息隊列的結構體箩兽,隊列的第一個消息指針msg_first
津肛,最后一個消息指針msg_last
,消息中有一個成員指針next
汗贫。
每一個消息中包含有哪些內(nèi)容:
Data 數(shù)據(jù)
Length 數(shù)據(jù)的長度
Type 數(shù)據(jù)的類型
消息的接收端可以根據(jù)消息的類型來接收身坐。
例如:
1----voltage data
2----電流數(shù)據(jù)
3----有功功率
二秸脱、消息隊列函數(shù)
消息隊列函數(shù)
1、msgget
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
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
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); // 加上循環(huán)看看有沒有寫進去
// delete message queue
msgctl(msgid, IPC_RMID, NULL);
system("ipcs -q");
return 0;
}
運行結果
4妥色、msgrcv
消息隊列中數(shù)據(jù)讀后搪花,數(shù)據(jù)也不存在了。
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;
}
運行結果