消息队列
1.特点
2.相关函数
ps:
消息队列实现单个进程的发送和读取
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
struct msgbuf
{
long mtype;//消息类型
char mtest[128];//消息内容容器
char ID[4];
};
int main()
{
struct msgbuf sendbuf,readbuf;
int msgid;//消息队列id
int readret;//读取到的字节数
msgid = msgget(IPC_PRIVATE,0755);
if(msgid == -1)
{
printf("create message queue failed !\n");
return -1;
}
printf("create message queue sucess ,msgid = %d\n",msgid);
system("ipcs -q");//终端打印出消息队列详细信息
//init msgbuf
sendbuf.mtype = 100;
printf("please input to message queue :\n");
fgets(sendbuf.mtest,128,stdin);//手动键盘输入内容
//send message to message queue
msgsnd(msgid,(void *)&sendbuf,strlen(sendbuf.mtest),0);
//read
memset(readbuf.mtest,0,128);//把readbuf中内容全部清零
readret = msgrcv(msgid,(void *)&readbuf,128,100,0);//读取
printf("message is %s\n",readbuf.mtest);
printf("total have %d byte\n",readret);
return 0;
}
运行结果:创建了id为524290的消息队列,键盘输入ni到该队列中,读取到内容为ni,并且为3个字节(还包含结束符‘\0’)。
我们再运行一次,发现524290消息队列中字节数为0,明明刚刚我们写入了内容,为什么此时为0呢???
原因:消息队列的性质就是如此,当从其中读取完数据后,他就会把该节点中的内容全部清除,但是该节点仍然存在鱼内核中。
ftok函数介绍
消息队列实现多个进程间的数据发送和读取
两个进程代码如下:
/*************msg_write.c*************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
struct msgbuf
{
long mtype;
char mtest[128];
char ID[4];
};
int main()
{
struct msgbuf sendbuf;
int msgid;
key_t key;
key = ftok("a.c",1);
msgid = msgget(key,IPC_CREAT|0755);
if(msgid == -1)
{
printf("create message queue failed !\n");
return -1;
}
printf("create message queue sucess ,msgid = %d\n",msgid);
system("ipcs -q");
//init msgbuf
sendbuf.mtype = 100;
while(1)
{
memset(sendbuf.mtest,0,128);
printf("please input to message queue :\n");
fgets(sendbuf.mtest,128,stdin);
msgsnd(msgid,(void *)&sendbuf,strlen(sendbuf.mtest),0); //send message to message queue
}
return 0;
}
/**************msg_read.c***********/
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
struct msgbuf
{
long mtype;
char mtest[128];
char ID[4];
};
int main()
{
struct msgbuf readbuf;
int msgid;
key_t key;
int readret;
key = ftok("a.c",1);
msgid = msgget(key,IPC_CREAT|0755);
if(msgid == -1)
{
printf("create message queue failed !\n");
return -1;
}
printf("create message queue sucess ,msgid = %d\n",msgid);
system("ipcs -q");
//init msgbuf
readbuf.mtype = 100;
while(1) //read
{
memset(readbuf.mtest,0,128);//把readbuf中内容全部清零
readret = msgrcv(msgid,(void *)&readbuf,128,100,0);
printf("message is %s\n",readbuf.mtest);
printf("total have %d byte\n",readret);
}
return 0;
}
编译:gcc msg_write.c -o msg_write
gcc msg_read.c -o msg_read
打开两个终端,分别运行 ./msg_write 和 ./msg_read
运行结果如下: