消息隊列(message queue)

/*
 *Filename: msgsnd.c
 *Description: 消息隊列的發送端
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>


#define BUFFERSIZE 1024


struct message
{
long int message_type;
char msg_text[BUFFERSIZE];
};


int main()
{
int msgqid; //創建消息隊列返回值
struct message msg;

//創建消息隊列
msgqid = msgget((key_t)1234,0666 | IPC_CREAT);
if(msgqid < 0)
{
perror("msgget error");
exit(-1);
}
//輸出提示信息
printf("Creat message queue %d\n",msgqid);

//向消息隊列寫數據
while(1)
{
printf("please input:");
scanf("%s",msg.msg_text);
msg.message_type = getpid();

//添加消息到消息隊列
if(msgsnd(msgqid,&msg,strlen(msg.msg_text),0) < 0)//寫入的長度是不包含數據類型的長度的
{
perror("msgsnd");
exit(-1);
}

//檢測結束標誌,當接收到end字符串
if(strncmp(msg.msg_text,"end",3) == 0)
{
//結束程序
break;
}
}
exit(0);
}


/**********************************************************************************************************************************************************************************/

/*
 *Filename: messagercv.c
 *Description: 消息隊列的接收端
 */


#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>


#define BUFFERSIZE 1024


struct message
{
long int message_type;
char msg_text[BUFFERSIZE];
};


int main()
{
int msgqid;
struct message msg;
msgqid = msgget((key_t)1234,IPC_CREAT | 0666);
if(msgqid < 0)
{
perror("msgget error");
exit(-1);
}
printf("Open the message queue %d\n",msgqid);


//當沒有讀到end結束子串時,保持循環
while(strncmp(msg.msg_text,"end",3))
{
memset(msg.msg_text,0,BUFFERSIZE);
if(msgrcv(msgqid,&msg,BUFFERSIZE,0,0) < 0)
{
perror("msgrcv error");
exit(-1);
}
printf("The message from process :%d\n",msg.message_type);
printf("The message:%s\n",msg.msg_text);
}

//消除消息隊列
if((msgctl(msgqid,IPC_RMID,NULL)) < 0)
{
perror("msgctl error");
exit(-1);


}
exit(0);

}


/***********************************************************************************************************************************************************************/

測試結果:

發佈了60 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章