函数ftok(),它可以根据不同的路径和关键字产生标准的key
---------------------------------------------------------- msg_com.h ----------------------------------------------------------- #ifndef __MSG_COM_H__ #define __MSG_COM_H__ #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 BUFFER_SIZE 512 struct message { long msg_type;//消息类型 char msg_text[BUFFER_SIZE];//消息正文 }; #endif ----------------------------------------------------- msgsnd.c #include "msg_com.h" /** *消息队列发送端 */ int main(int argc, char **argv) { int qid; key_t key; struct message msg; //根据不同的路径和关键字产生标准的key if ((key = ftok(".", 'c')) == -1){ perror("ftok"); exit(1); } //创建消息队列 qid = msgget(key, IPC_CREAT | 0666); if (qid == -1){ perror("msgget"); exit(1); } printf("Open queue %d\n", qid); while(1) { printf("Enter some message to the queue(quit to exit):\n"); if(fgets(msg.msg_text, BUFFER_SIZE, stdin) == NULL) { puts("fgets"); exit(1); } msg.msg_type = getpid(); //添加消息到消息队列 if((msgsnd(qid, &msg, strlen(msg.msg_text), 0)) < 0) { perror("msgsnd"); exit(1); } if (strncmp(msg.msg_text, "quit", 4) == 0) { break; } } exit(0); } ----------------------------------------------------- msgrcv.c #include "msg_com.h" /** *消息队列接收端 */ int main(int argc, char **argv) { int qid; key_t key; struct message msg; if ((key=ftok(".", 'c')) == -1){ perror("ftok"); exit(1); } //创建消息队列 if ((qid = msgget(key, IPC_CREAT|0666)) == -1){ perror("msgget"); exit(1); } printf("Open queue %d\n", qid); do { //读取消息队列 memset(msg.msg_text, 0, BUFFER_SIZE); if (msgrcv(qid, (void *)&msg, BUFFER_SIZE, 0, 0) < 0) { perror("msgrcv"); exit(1); } printf("the message from process %ld: %s\n", msg.msg_type, msg.msg_text); } while(strncmp(msg.msg_text, "quit", 4)); //从系统内核中移走消息队列 if ((msgctl(qid, IPC_RMID, NULL)) < 0) { perror("msgctl"); exit(1); } exit(0); } -------------------------------------------------------------------- 测试结果 msgque# ./msgsnd Open queue 163840 Enter some message to the queue(quit to exit): good day Enter some message to the queue(quit to exit): day is good day Enter some message to the queue(quit to exit): time is money Enter some message to the queue(quit to exit): quit msgque# ./msgrcv Open queue 163840 the message from process 6150: good day the message from process 6150: day is good day the message from process 6150: time is money the message from process 6150: quit