進程間通信—消息隊列(一)

消息隊列基本概念:

消息隊列是系統內核地址空間中的一個內部的鏈表。消息可以按照順序發送到隊列中,

也可以以幾種不同的方式從隊列中讀取。每一個消息隊列用一個唯一的IPC標識符表示。

我們來實現一個簡單的消息隊列的工具,用於創建消息隊列、發送、讀取消息、

改變權限以及刪除消息隊列。

綜合實例:msgtool

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_SEND_SIZE 80
struct mymsgbuf
{
	long mtype;
	char mtext[MAX_SEND_SIZE];
};
void send_message(int qid,struct mymsgbuf *qbuf,long type,char *text);
void read_message(int qid,struct mymsgbuf *qbuf,long type);
void remove_queue(int qid);
void change_queue_mode(int qid,char *mode);
void usage(void);
int main(int argc,char **argv)
{
	key_t key;
	int msgqueue_id;
	struct mymsgbuf qbuf;
	if(argc == 1)
	{
		usage();
	}
	key=ftok(".",'m');
	if((msgqueue_id = msgget(key,IPC_CREAT|0777))==-1)
	{
		perror("msgget");
		exit(1);
	}
	printf("message queue id=[%d]\n",msgqueue_id);
	switch(tolower(argv[1][0]))
	{
		case 's':
			if(argc < 4)
			{
				usage();
				break;
			}
			send_message(msgqueue_id,(struct mymsgbuf *)&qbuf,atol(argv[2]),argv[3]);
			break;
		case 'r':
			if(argc < 3)
			{
				usage();
				break;
			}
			read_message(msgqueue_id,&qbuf,atol(argv[2]));
			break;
		case 'd':
			remove_queue(msgqueue_id);
			break;
			case 'm':
			if(argc < 3)
			{
				usage();
				break;
			}
			change_queue_mode(msgqueue_id,argv[2]);
			break;
		default:
			usage();
	}
	return 0;
}
void send_message(int qid,struct mymsgbuf *qbuf,long type,char *text)
{
	printf("Sending a message...\n");
	qbuf->mtype=type;
	strcpy(qbuf->mtext,text);
	if((msgsnd(qid,(struct msgbuf *)qbuf,strlen(qbuf->mtext)+1,0))==-1)
	{
		perror("msgsnd");
		exit(0);
	}
}
void read_message(int qid,struct mymsgbuf *qbuf,long type)
{
	printf("Reading a message...\n");
	qbuf->mtype=type;
	msgrcv(qid,(struct msgbuf *)qbuf,MAX_SEND_SIZE,type,0);
	printf("Type:%ld Text:%s\n",qbuf->mtype,qbuf->mtext);
}
void remove_queue(int qid)
{
	msgctl(qid,IPC_RMID,0);
}

void change_queue_mode(int qid,char *mode)
{
	struct msqid_ds myqueue_ds;
	msgctl(qid,IPC_STAT,&myqueue_ds);
	sscanf(mode,"%ho",&myqueue_ds.msg_perm.mode);
	msgctl(qid,IPC_SET,&myqueue_ds);
}
void usage(void)
{
	fprintf(stderr,"msgtool -A utility for tinking with msgqueue\n");
	fprintf(stderr,"USAGE:msgtool (s)end <type> <messagetext>\n");
	fprintf(stderr,"(r)ecv <type>\n");
	fprintf(stderr,"(d)elete\n");
	fprintf(stderr,"(m)ode <octal mode>\n");
	exit(1);
}



一個終端發送消息:

./msgtool s 1 "Hello"


一個終端接受消息:

./msgtool r 0


這時將收到消息:Hello。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章