消息队列示例

消息队列是内核中的一个链表。使用方法类似有名管道。

消息队列使用完毕后,不释放永久存在内核中,除非重启。

发送消息:

/*************************************************************************
    > File Name: msg_snd.c
    > Author: CC
    > Mail: [email protected] 
    > Created Time: 2018年09月09日 星期日 12时01分53秒
 ************************************************************************/

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/msg.h>
//定义消息结构体,包括类型和数据
typedef struct{
	long type;
	int start;
	int end;
}MSG;

int main(int argc,char *argv[])
{
	if(argc < 2){
		printf("Usage: %s key \n",argv[0]);
		exit(1);
	}
	//系统自动分配额
	//key_t = IPC_PRIVATE;
	//根据函数算法生成
	//key_t = ftok(argv[1],0);
	key_t key = atoi(argv[1]);//将传入的字符串进行转化
	printf("key: %d\n",key);

	//创建消息队列
	int msg_id;
	if((msg_id = msgget(key,IPC_CREAT|IPC_EXCL|0777)) < 0){
		perror("msgget error1\n");
		exit(1);
	}
	printf("msg id : %d\n",msg_id);

	//定义要发送的消息类型
	MSG m1 = {1,1,100};
	MSG m2 = {2,2,200};
	MSG m3 = {3,3,300};
	MSG m4 = {4,4,400};
	MSG m5 = {5,5,500};
	MSG m6 = {6,6,600};
	
	//发送消息到消息队列

	if(msgsnd(msg_id,&m1,sizeof(MSG)-sizeof(long),IPC_NOWAIT)<0){
			perror("msgsnd error\n");
			exit(1);
		}
	
	if(msgsnd(msg_id,&m2,sizeof(MSG)-sizeof(long),IPC_NOWAIT)<0){
			perror("msgsnd error\n");
			exit(1);
		}
	if(msgsnd(msg_id,&m3,sizeof(MSG)-sizeof(long),IPC_NOWAIT)<0){
			perror("msgsnd error\n");
			exit(1);
		}
	if(msgsnd(msg_id,&m4,sizeof(MSG)-sizeof(long),IPC_NOWAIT)<0){
			perror("msgsnd error\n");
			exit(1);
		}
	if(msgsnd(msg_id,&m5,sizeof(MSG)-sizeof(long),IPC_NOWAIT)<0){
			perror("msgsnd error\n");
			exit(1);
		}
	if(msgsnd(msg_id,&m6,sizeof(MSG)-sizeof(long),IPC_NOWAIT)<0){
			perror("msgsnd error\n");
			exit(1);
		}

	//发送后去获得消息队列的总数
	struct msqid_ds ds;
	if(msgctl(msg_id,IPC_STAT,&ds) < 0){
		perror("msgctl error");
	}
	printf("msg total: %ld\n",ds.msg_qnum);

	return 0;
}

消息接收:

/*************************************************************************
    > File Name: msg_rcv.c
    > Author: CC
    > Mail: [email protected] 
    > Created Time: 2018年09月09日 星期日 12时39分12秒
 ************************************************************************/

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

typedef struct{
	long type;
	int start;
	int end;
}MSG;

int main(int argc,char *argv[])
{
	if(argc < 3){
		printf("Usage: %s key type \n",argv[0]);
		exit(1);
	}

	key_t key = atoi(argv[1]);
	long type = atoi(argv[2]);

	//获得指定的消息队列
	int msg_id;
	if((msg_id = msgget(key,0777)) < 0){
		perror("msgget error!\n");
		exit(1);
	}
	printf("msg id: %d\n",msg_id);

	MSG m;
	if(msgrcv(msg_id,&m,sizeof(MSG)-sizeof(long),type,IPC_NOWAIT) <0){
		perror("msgrcv error!\n");
		exit(1);
	}else{
		printf("msgtype: %ld start: %d end :%d\n",m.type,m.start,m.end);
	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/baidu_33879812/article/details/82557444