易网时代-编程资源站
Welcome
微信登录
编程资源
图片资源库
蚂蚁家优选
PDF转换器
软件资源
软件开发
、
小程序制作
、
系统集成与运维
、
空间租用
、
硬件开发
、
视频监控
、
技术咨询与支持
——联系电话:0311-88999002/88999003
首页
/
操作系统
/
Linux
/
Linux消息队列编程实例
/*
创建消息队列msgget( )
调整消息队列的参数msgctl(msgid,IPC_SET,struct msqid_ds* )
发送一条消息msgsnd( )
接受一条消息msgrcv( )
移除一条消息msgctl( msgid,IPC_RMID,NULL )
*/
/*创建一个消息队列,并调整其大小,发送一条消息
再取出该条消息,最后移除该消息队列
*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#define MAX_LINE 80
#define MY_MQ_ID 1233
/*消息结构体的一般形式如下:
typedef struct
{
long type; //用于存放消息代码,必须位于首位
char message[ LENGHT+1 ];
}MSG_TYPE_T;
*/
typedef
struct
{
long
type;
float
fval;
unsigned
int
uival;
char
strval[ MAX_LINE+1 ];
}MY_TYPE_T;
int
main( )
{
int
msgid,ret;
//create the message queue with the id MY_MQ_ID
msgid=msgget( MY_MQ_ID,0666|IPC_CREAT );
if
( msgid>=0 )
printf(
"Created a Message Queue,message queue identifier is %d "
,msgid );
//modify the size of message queue
struct
msqid_ds buf;
ret=msgctl( msgid,IPC_STAT,&buf );
printf(
"The origianl size of queue is %d "
,buf.msg_qbytes );
buf.msg_qbytes=4096;
ret=msgctl( msgid,IPC_SET,&buf );
if
( ret==0 )
printf(
"Size sucessfully changed for queue,message queue identifier is %d "
,msgid );
//send a message
MY_TYPE_T myMessage;
myMessage.type=1L;
//消息的类型,msgrcv会用到
myMessage.fval=128.256;
myMessage.uival=512;
strncpy( myMessage.strval,
"This is a test. "
,MAX_LINE );
ret=msgsnd( msgid,(
struct
msgbuf* )&myMessage,
sizeof
( MY_TYPE_T ),0 );
//0是消息旗标
if
( ret!=-1 )
printf(
"Message send successfully. "
);
//read a message
MY_TYPE_T recMessage;
ret=msgrcv( msgid,(
struct
msgbuf* )&recMessage,
sizeof
(MY_TYPE_T),1,0 );
//这个地方Message Type要和欲接受的消息类型相同
if
( ret!=-1 )
{
printf(
" Read a message from the queue "
);
printf(
"Message Type:%ld "
,recMessage.type );
printf(
"Float value:%f "
,recMessage.fval );
printf(
"Uint value:%d "
,recMessage.uival );
printf(
"String value:%s "
,recMessage.strval );
}
//destroy a message queue
ret=msgctl( msgid,IPC_RMID,NULL );
if
( ret!=-1 )
printf(
"Message queue %d sucessfully removed. "
,msgid );
return
0;
}
/*还有很多实际创建时的细节,可以通过man进行查找
使用命令来查看IPC队列:
ipcs -q
ipcs -q -i $msgid
ipcrm -q $msgid
*/
收藏该网址
版权所有©石家庄振强科技有限公司2024
冀ICP备08103738号-5
网站地图