进程通信--消息队列

一.消息队列

消息队列是提供一种从一个进程想另一个进程发送数据块的方法。用这种方法解决命名管道的同步和阻塞问题。不同于管道的是,消息队列是基于消息的,而管道是基于字节流的,并且消息队列的对去不一定是先入先出。同样,消息队列也存在消息的最大 长度(MSGMAX),每个消息队列总的字节数也是有上限的(MSGMNB),系统上消息队列的总数也有一个上限(MSGMNI)。

测试机器的三个上限值:



二.IPC对象数据结构

/* Obsolete, used only for backwards compatibility and libc5 compiles */
struct ipc_perm
{
	__kernel_key_t	key;
	__kernel_uid_t	uid;
	__kernel_gid_t	gid;
	__kernel_uid_t	cuid;
	__kernel_gid_t	cgid;
	__kernel_mode_t	mode; 
	unsigned short	seq;
};
key值:key_t ftok(const char *pathname, int proj_id); // 函数ftok把⼀一个已存在的路径名和⼀一个整数标识得转换成⼀一个key_t值,称为IPC键

   On success, the generated key_t value is returned.  On failure  -1  is  returned,  with errno indicating the error as for the stat(2) system call.成功返回key,否则返回-1。


三.消息队列结构

/* Obsolete, used only for backwards compatibility and libc5 compiles */
struct msqid_ds {
	struct ipc_perm msg_perm;
	struct msg *msg_first;		/* first message on queue,unused  */
	struct msg *msg_last;		/* last message in queue,unused */
	__kernel_time_t msg_stime;	/* last msgsnd time */
	__kernel_time_t msg_rtime;	/* last msgrcv time */
	__kernel_time_t msg_ctime;	/* last change time */
	unsigned long  msg_lcbytes;	/* Reuse junk fields for 32 bit */
	unsigned long  msg_lqbytes;	/* ditto */
	unsigned short msg_cbytes;	/* current number of bytes on queue */
	unsigned short msg_qnum;	/* number of messages in queue */
	unsigned short msg_qbytes;	/* max number of bytes on queue */
	__kernel_ipc_pid_t msg_lspid;	/* pid of last msgsnd */
	__kernel_ipc_pid_t msg_lrpid;	/* last receive pid */
};
消息队列是用链表实现的。

四.消息队列的函数

  1.生成新消息队列或者取得已存在的消息队列

    int msgget(ket_t key,int msgflg);


           key:可以认为是一个端口号,也可以由函数ftok生成。    

           msgflg:              

            IPC_CREAT:如果IPC不存在,则创建一个IPC资源,否则打开操作。                                   

            IPC_EXCL:只有在共享内存不存在的时候,新的共享内存才建立,否则就产生错误。 如果单独使用IPC_CREAT   XXXget()函数要么返回一个已经存在的共享内存的操作符,要 么返回一个新建的共享内存的标识符。 如果将IPC_CREAT和IPC_EXCL标志一起使用,XXXget()将返回一个新建的IPC标识符 ;如果该IPC资源已存在,或者返回-1。      IPC_EXEL标志本身并没有太大的意义,但是和IPC_CREAT标志一起使用可以用来保证所得的对象是新建的,而不是打开已有的对象。 

        返回值:返回msgid。

2.向队列读/写消息

  msgrcv取消息:ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); 

  msgsnd读消息:int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);

     msqid:消息队列的标识码。     

   msgp:指向消息缓冲区的指针,此位置用来暂时存储发送和接收的消息,是一个用户可定义的通用结构,形态如下:

struct msgstru
{
    long mtype;//大于0
    char mtext[_SIZE_]; //_SIZE_ 用户指定大小
}

  msgsz:消息的大小。   

  msgtyp:从消息队列内读取的消息形态。如果值为零,则表示消息队列中的所有消息都会被读取。   

  msgflg:用来指明核心程序在队列没有数据的情况下所应采取的行动。如果msgflg和常数IPC_NOWAIT合用,则在msgsnd()执行时若是消息队列已满,则msgsnd()将不会阻塞,而会立即返回-1,如果执行的是msgrcv(),则在消息队列呈空时,不做等待马上返回-1,并设定 错误码为ENOMSG。当msgflg为0时,msgsnd()及msgrcv()在队列呈满或呈空的情形时,采取 阻塞等待的处理模式。 


五.使用消息队列模拟实现一个客户端--服务端的通信

    1.定义头文件:


头文件中定义五个接口,分别为:

int creat_msg_queue();  //创建一个消息队列

int get_msg_queue();   //获得消息队列的msg_id


int send_msg(int msg_id,int send_type,const char* msg);  //发送消息


int recv_msg(int msg_id,int recv_type,char* msg_out);  //接收消息


int destroy_queue(int msg_id);  //销毁队列



2.server.c



a.创建消息队列,接收客户端发送的消息,同时给客户端发送消息。

3.客户端


a.获取msg_id,接收服务端发送的消息,同时给客户端反馈

六.Makefile的编写


因为要生成两个可执行程序,所以使用伪目标all。

$@(依赖关系中代表目标文件) $^(依赖关系中:右边的所有内容)

七.代码实现

1.comm.h

#pragma once

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

#define _PATH_NAME_ "/tmp"
#define _PROJ_ID_ 0x6666
#define _SIZE_ 1024

extern int server_type;
extern int client_type;


struct msgbuf
{
	long mtype;
	char mtext[_SIZE_];
};

int creat_msg_queue();
int get_msg_queue();
//int creat_msg_queue(int msg_id);
int send_msg(int msg_id,int send_type,const char* msg);
int recv_msg(int msg_id,int recv_type,char* msg_out);
int destroy_queue(int msg_id);




2.comm.c

#include"comm.h"

int server_type = 1;
int client_type = 2;


static int comm_msg_queue(int flags)
{
	key_t _key = ftok(_PATH_NAME_,_PROJ_ID_);
	if(_key < 0)
	{
		printf("%d : %s",errno,strerror(errno));
		return -1;
	}

	int msg_id = msgget(_key,flags);
	//int msg_id = msgget(_key,IPC_CREAT | IPC_EXCL | 0666);
	return msg_id;
}

int creat_msg_queue()
{
	int flags = IPC_CREAT | IPC_EXCL | 0666;
	return comm_msg_queue(flags);
}

int get_msg_queue()
{
	int flags = IPC_CREAT;
	return comm_msg_queue(flags);
}

int destroy_queue(int msg_id)
{
	if(msgctl(msg_id,IPC_RMID,NULL) != 0)
	{
		printf("%d : %s",errno,strerror(errno));
		return -1;
	}

	return 0;
}

int send_msg(int msg_id,int send_type,const char* msg)
{
	struct msgbuf _buf;
	_buf.mtype = send_type;
	strncpy(_buf.mtext,msg,strlen(msg)+1);

	if(msgsnd(msg_id,&_buf,sizeof(_buf.mtext),0) < 0)
	{
		printf("%d : %s",errno,strerror(errno));
	    return -1;
	}
	return 0;
}

int recv_msg(int msg_id,int recv_type,char* msg_out)
{
	struct msgbuf _buf;
	_buf.mtype = 0;
	memset(_buf.mtext,'\0',sizeof(_buf.mtext));

	if(msgrcv(msg_id,&_buf,sizeof(_buf.mtext),recv_type,0) < 0)
	{
		printf("%d : %s",errno,strerror(errno));
	    return -1;
	}

	strcpy(msg_out,_buf.mtext);
	return 0;
}



3.server.c

#include"comm.h"

int main()
{
	int msg_id = creat_msg_queue();
	if(msg_id <0)
	{
		printf("%d : %s\n",errno,strerror(errno));
		return 1;
	}

	char buf[_SIZE_];
	while(1)
	{
		memset(buf,'\0',sizeof(buf));
		recv_msg(msg_id,client_type,buf);
		printf("client:%s\n",buf);
		if(strcasecmp(buf,"quit") == 0)
		{
			break;
		}

		printf("client say done,Please Enter# ");
		fflush(stdout);
		ssize_t _s = read(0,buf,sizeof(buf)-1);
		if(_s > 0)
		{
			buf[_s - 1] = '\0';
		}

		send_msg(msg_id,server_type,buf);

	}

	destroy_queue(msg_id);
	return 0;
}


4.client.c

#include"comm.h"

int main()
{
	//int msg_id = creat_msg_queue();
	
	//if(msg_id <0)
	//{
	//	printf("%d : %s\n",errno,strerror(errno));
	//	return 1;
	//}
	//
	//
	int msg_id = get_msg_queue();

	char buf[_SIZE_];
	while(1)
	{
		printf("Please Enter:");
		fflush(stdout);
		ssize_t _s = read(0,buf,sizeof(buf)-1);
		if(_s >0 )
		{
			buf[_s - 1] = '\0';
		}
		send_msg(msg_id,client_type,buf);
		if(strcasecmp(buf,"quit") == 0)
		{
			break;
		}

		memset(buf,'\0',sizeof(buf));
		recv_msg(msg_id,server_type,buf);
		printf("server# %s\n",buf);
	}

	return 0;
}


八.测试结果



          以上就是本人在学习过程中的一些经验总结。当然,本人能力有限,难免会有纰漏,希望大家可以指正。












  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值