消息队列是类似于管道,又类似于共享内存的进程间通信的方式.该方式使用的是采用链式存储的方式来存储消息的,而且读取过了以后该消息会被删除.而且消息会被编号,可以发送和读取不同编号的消息,方便传递不通的消息.而创建的过程和共享内存类似,但是不用进行映射,直接将获取的Id使用即可.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <string.h>
struct msgbuf {
long mtype; // 消息类型,必须 > 0
char mtext[8]; // 消息文本
};
int main(int argc,char *argv[]){
int key = 0;
int msqid = 0;
struct msgbuf buf;
strcpy(buf.mtext,"hello");//要发送的信息
buf.mtype = 1;//信息的类型
key = ftok("sig.c",0);
msqid = msgget(key,IPC_CREAT | 0666);
if(msqid > 0){
printf("message queue succeed\n");
}else{
printf("creat failed\n");
return -1;
}
int i = 0;
while(i < 6){
msgsnd(msqid,(void *)&buf,strlen(buf.mtext),0);
sleep(2);
i++;
}
msgctl(msqid,IPC_RMID,NULL);
return 0;
}
读消息队列:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <string.h>
struct msgbuf {
long mtype; // 消息类型,必须 > 0
char mtext[8]; // 消息文本
};
int main(int argc,char *argv[]){
int key = 0;
int msqid = 0;
struct msgbuf buf;
buf.mtype = 1;
strcpy(buf.mtext,"hello");
key = ftok("sig.c",0);
msqid = msgget(key,IPC_CREAT | 0666);
if(msqid > 0){
printf("message queue succeed\n");
}else{
printf("creat failed\n");
msgctl(msqid,IPC_RMID,NULL);
return -1;
}
int i = 0;
while(i < 6){
sleep(2);
msgrcv(msqid,(void *)&buf,strlen(buf.mtext),0,0);
i++;
printf("%s\n",buf.mtext);
}
msgctl(msqid,IPC_RMID,NULL);
return 0;
}
原文:http://www.cnblogs.com/CHYI1/p/5406295.html