消息队列:
1,消息队列的创建与打开
原型:int msgget(key_t key, int msgflg);
2,向消息队列中发送消息
原型:int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
3,从消息队列中接收消息
原型:ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
4,消息队列的控制
原型:int msgctl(int msqid, int cmd, struct msqid_ds *buf);
系统建立IPC通讯(如消息队列、共享内存时)必须指定一个ID值 。通常情况下,该id值通过ftok函数得到 。
参数说明:
fname就是指定的文档名
id是子序号。
ftok原型如下:
key_t ftok( char * fname, int id )
消息队列实现通信:
send:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdio.h>
struct msgBuf {
long mtype;
char mtext[128];
};
int main()
{
struct msgBuf readBuf;
struct msgBuf sendBuf = {888,“this is from send”};
key_t key;
key = ftok(".",‘z’); //获取key “.” 表示当前路径
printf(“key=%x\n”,key);
int msgId = msgget(key,IPC_CREAT|0777);
if(msgId == -1){
printf("creat faul\n");
}
if(msgsnd(msgId,&sendBuf,strlen(sendBuf.mtext),0)==-1){
printf("send fail\n");
}
if(msgrcv(msgId,&readBuf,sizeof(readBuf.mtext),988,0)==-1){
printf("reserve fail\n");
}
printf("return reserve:%s\n",readBuf.mtext);
msgctl(msgId,IPC_RMID,NULL);
return 0;
}
server:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
struct msgBuf{
long mtype;
char mtext[128];
};
int main()
{
struct msgBuf readBuf ;
struct msgBuf sendBuf ={988,"thamk you for reach"};
int msgId;
key_t key;
key = ftok(".",'z'); //获取key
printf("key=%x\n",key);
msgId = msgget(key,IPC_CREAT|0777);
if(msgId == -1){
printf("creat fail\n");
}
if(msgrcv(msgId,&readBuf,sizeof(readBuf.mtext),888,0)==-1){
printf("receve fail\n");
}
printf("read from send:%s\n",readBuf.mtext);
if(msgsnd(msgId,&sendBuf,sizeof(sendBuf.mtext),0) == -1){
printf("send fail\n");
}
msgctl(msgId,IPC_RMID,NULL);
return 0;
}
运行结果为: