消息队列——The message queue
//消息队列:数据通讯
// 点对多,离线通讯。
// ftok();索取KEY值
//
// msgget();创建
// msgctl();删除
// msgsnd();发送
// msqrcv();接收
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "proto.h"
int main()
{
int msgid; //
key_t key;
struct msg_st sbuf;
// 获取消息队列关联的键。
key = ftok(KEYPATH,KEYPROJ);
if(key < 0)
{
perror("ftok()");
exit(1);
}
//int msgget(key_t key, int msgflg);
//参数msgflg为:消息队列的建立标志和存取权限
msgid = msgget(key,0);
//success 返回队列标识,failed ,return -1;
if(msgid < 0)
{
perror("msgget()");
exit(1);
}
//mtype :从消息队列内读取的消息形态。(0:消息队列中所有消息都会被
//读取)
sbuf.mtype = 1; /*!!*/
strcpy(sbuf.name,"Alan");
sbuf.math = rand()%100;
sbuf.chinese = rand()%100;
if(msgsnd(msgid,&sbuf,sizeof(sbuf)-sizeof(long),0) < 0)
{
perror("msgsnd");
exit(1);
}
puts("ok!");
exit(0);
}
----------------------------------------------------------------------------------------------------------------
// 消息队列
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "proto.h"
int main()
{
int msgid;
struct msg_st rbuf;
key_t key;
key = ftok(KEYPATH,KEYPROJ);
if(key < 0)
{
perror("ftok()");
exit(1);
}
msgid = msgget(key,IPC_CREAT|0600);
if(msgid < 0)
{
perror("msgget()");
exit(1);
}
while(1)
{
if(msgrcv(msgid,&rbuf,sizeof(rbuf)-sizeof(long),0,0) < 0)
{
perror("msgrcv()");
exit(1);
}
printf("Name:%s\n",rbuf.name);
printf("Math:%d\n",rbuf.math);
printf("Chinese:%d\n",rbuf.chinese);
}
msgctl(msgid,IPC_RMID,NULL);
exit(0);
}
--------------------------------------------------------------------------------------------------------
#ifndef PROTO_H__
#define PROTO_H__
#define KEYPATH "/etc/services"
#define KEYPROJ 'S'
#define NAMESIZE 32
struct msg_st
{
long mtype;
char name[NAMESIZE];
int math;
int chinese;
};
#endif