进程间的通信---消息队列

来源:互联网 发布:算法导论 kindle 编辑:程序博客网 时间:2024/05/19 09:49

消息队列:队列是先进先出,把写入的消息按队列的方式排列,然后读取消息时按队列性质读取,或按指定的类型号读取;

实现消息队列的步骤:

1.获取key值,

2.创建消息队列,取得消息队列的ID;

3.向消息队列里写入消息;

4.读取消息队列的消息;

5.删除消息队列;


读端代码:

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

struct msgbuf
{
long type;
char buff[128];
};

int main(int argc, const char *argv[])
{
key_t key;
int qid;
long type = 0;
int len;
struct msgbuf msg;
len = sizeof(struct msgbuf) - sizeof(long);
//获取key值
if((key = ftok("./",'a')) < 0)
{
perror("ftok fail\n");
return -1;
}
//创建消息队列
if((qid = msgget(key,IPC_CREAT | 0666)) < 0)
{
perror("msgget fail\n");
return -1;
}
//接受消息
while(1)
{
if(msgrcv(qid,&msg,len,0,0) < 0)
{
perror("read fail\n");
return -1;
}
if(strcmp(msg.buff,"quit") == 0)
{
break;
}
printf("读取的消息是:%s\n",msg.buff);
}

printf("消息已经读取完毕!\n");

//删除消息队列
if(msgctl(qid,IPC_RMID,NULL) < 0)
{
perror("delete fail\n");
exit(-1);
}
return 0;
}


写端:

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

struct msgbuf
{
long type;
char buff[128];
};

int main(int argc, const char *argv[])
{
key_t key;
int qid;
int len;
struct msgbuf msg;
msg.type = 0;
len = sizeof(struct msgbuf) - sizeof(long);
//获取key值
if((key = ftok("./",'a')) < 0)
{
perror("ftok fail\n");
return -1;
}
//创建消息队列
if((qid = msgget(key,IPC_CREAT | 0666)) < 0)
{
perror("msgget fail\n");
return -1;
}
//发送消息
while(1)
{
printf("请输入发送的消息:");
fflush(stdout);
scanf("%s",msg.buff);


msgsnd(qid,&msg,len,0);
if(strcmp(msg.buff,"quit") == 0)
break;
msg.type++;
}

//删除消息队列
if(msgctl(qid,IPC_RMID,NULL) < 0)
{
perror("delete fail\n");
exit(-1);
}
printf("发送端结束\n");
return 0;
}