天天看点

消息队列示例

消息队列是将消息按队列的方式组织成的链表,每个消息都是其中的一个节点。

消息队列的操作函数有一下几个:

int  msgget(key_t key, int msgflg)    //创建1个消息队列

int  msgsnd(int msqid, const void *msgptr, int msgsz , int msgflg)  //发送消息到消息队列中

int  msgrcv (int msqid,void *msgptr, int msgsz ,long msgtyp, int msgflag) //从消息队列中读取一个消息

int msgctl (int msqid, int cmd ,struct msqid_ds *buf)  //消息队列控制函数

示例如下:

#include <string.h>

#include <sys/types.h>

#include <sys/msg.h>

#include <unistd.h>

#include <stdlib.h>

#include <stdio.h>

int main(void)

{

int msg_id,msg_flags;   

int reval;

char send_msg[64];

msg_flags = IPC_CREAT | 0666;  

msg_id = msgget((key_t)456,msg_flags);  //创建消息队列并返回消息队列id

if(-1 == msg_id)        //判断是否创建成功(返回-1 为失败)

{

printf("msg create error.\n");

exit(EXIT_FAILURE);

}

memset(send_msg,0,64); 

sprintf(send_msg,"hi, I'm %d.\n",getpid()); // 打印字符串到send_msg 中

reval = msgsnd(msg_id,send_msg,sizeof(send_msg),0);//将send_msg中的消息发送到消息队列中,消息队列的id为msg_id

if(-1 == reval)  //发送消息失败返回-1

{

printf("message send error.\n");

exit(EXIT_FAILURE);

}

else

printf("Send message:%s\n",send_msg);  

return 0;

}

#include <string.h>

#include <sys/types.h>

#include <sys/msg.h>

#include <unistd.h>

#include <stdlib.h>

#include <stdio.h>

int main(void)

{

int msg_id,msg_flags;   

int reval;

char send_msg[64];

msg_flags = IPC_CREAT | 0666;  

msg_id = msgget((key_t)456,msg_flags);

if(-1 == msg_id)        //判断是否创建成功(返回-1 为失败)

{

printf("msg create error.\n");

exit(EXIT_FAILURE);

}

memset(send_msg,0,64); 

reval = msgrcv(msg_id,send_msg,64,0,0);//从消息队列中读取一个消息

if(-1 == reval)  //发送消息失败返回-1

{

printf("message send error.\n");

exit(EXIT_FAILURE);

}

else

printf("Received message:%s\n",send_msg); 

reval = msgctl(msg_id,IPC_RMID,0);

if(-1 == reval)

{

printf("remove msg queue error\n");

exit(EXIT_FAILURE);

}

return 0;

}

继续阅读