消息队列貌似慢慢被程序员们所遗忘了,在进程间通信中用到它的甚少,不过平时学习中我们也得了解下消息队列的用法。下面是本人写的两个代码,一个是读进程,一个是写进程。关于消息队列的具体函数及参数配置,还得去看W·Richard·Stevens写的《网络编程卷2:进程间通信》。
两个程序通过gcc编译后,运行,在写端打入自己想要的字符串,在读端就会打印出来。
写消息的进程:
#include<sys/msg.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<string.h>
#define DATALEN 100
struct megbuf
{
long mtype;
char mtext[DATALEN];
};
int main()
{
int msqid;
struct megbuf buf;
int ret;
int key;
int sendlength;
key = ftok("meg.tmp",'a');
msqid = msgget(key,IPC_CREAT|0666);
if(msqid < 0)
{
perror("get message queue error\n");
return -1;
}
while(1)
{
buf.mtype = 23;
gets(buf.mtext);
// strcpy(buf.mtext,"hello world!");
sendlength = sizeof(struct megbuf) - sizeof(long);
ret = msgsnd(msqid,&buf,sendlength,0);
if(ret < 0)
{
perror("send message err\n");
return -1;
}
}
// system("ipcs -q");
return 0;
}
读消息进程:
#include<sys/msg.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<string.h>
#define DATALEN 100
typedef struct megbuf
{
long mtype;
char mtext[DATALEN];
}Message;
int main()
{
int msqid;
Message buf;
int ret;
int key;
int mtype;
int recvlength;
key = ftok("msg.tmp",'a');
msqid = msgget(key,0666);
if(msqid < 0)
{
perror("get message queue err\n");
return -1;
}
recvlength = sizeof(Message) - sizeof(long);
memset(&buf,0,sizeof(Message));
while(1)
{
mtype = 23;
ret = msgrcv(msqid,&buf,recvlength,mtype,0);
if(ret < 0)
{
perror("recv message error\n");
return -1;
}
printf("message = %s\n",buf.mtext);
}
// system("ipcs -q");
return 0;
}