所谓消息队列就是指一个消息链表。
int msgget(key_t, int flag):创建和打开队列
int msgsnd(int msqid, struct msgbuf *msgp, size_t msgsz, int flag):发送消息,msgid是消息队列的id,msgp是消息内容所在的缓冲区,msgsz是消息的大小,msgflg是标志。
int msgrcv(int msqid, struct msgbuf *msgp, size_t msgsz, long msgtyp, int flag):接受消息,msgtyp是期望接收的消息类型。
int msgctl(int msqid, int cmd, struct msqid_ds *buf):控制
#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define BUFSZ 512 struct message{ //消息结构体 long msg_type; char msg_text[BUFSZ]; }; int main() { int qid; key_t key; int len; struct message msg; if((key=ftok(".",'a'))==-1) //ftok获得一个key { perror("ftok"); exit(1); } if((qid=msgget(key,IPC_CREAT|0666))==-1){ //创建一个消息队列 perror("msgget"); exit(1); } printf("opened queue %d\n",qid); puts("Please enter the message to queue:"); if((fgets(msg.msg_text,BUFSZ,stdin))==NULL) // 从标准输入获取输入 { puts("no message"); exit(1); } msg.msg_type = getpid(); len = strlen(msg.msg_text); if((msgsnd(qid,&msg,len,0))<0){ //发送消息 perror("message posted"); exit(1); } if(msgrcv(qid,&msg,BUFSZ,0,0)<0){ //接收消息 perror("msgrcv"); exit(1); } printf("message is:%s\n",(&msg)->msg_text); if((msgctl(qid,IPC_RMID,NULL))<0){ //删除消息 perror("msgctl"); exit(1); } exit(0); }