练习代码,写个消息队列发送接收
2013-09-26 17:31
519 查看
#include <stdio.h> #include <sys/msg.h> #include <sys/types.h> #include <sys/ipc.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include "message.h" int qid=0; int message_init() { key_t key = ftok(MSG_PATH, MSG_PJID); if(key == -1) { perror("ftok failed"); exit(EXIT_FAILURE); } if((qid = msgget(key, IPC_CREAT | 0666)) == -1) { perror("create message queue failed"); exit(EXIT_FAILURE); } return qid; } int message_send(int msgid, const STRUCT_MSG_BUF* pmsg, int flag) { if( pmsg != NULL && pmsg->length >0 ) { if( msgsnd(msgid, pmsg, sizeof(STRUCT_MSG_BUF), 0) == -1) { perror("send msg to message queue failed"); exit(EXIT_FAILURE); } } return 0; } int message_receive(int msgid, STRUCT_MSG_BUF* pmsg, int flag) { if( msgrcv(msgid, pmsg, sizeof(STRUCT_MSG_BUF), 0, flag) == -1 ) { perror("receive msg from message queue failed"); exit(EXIT_FAILURE); } return 0; }
#ifndef __MESSAGE_H #define __MESSAGE_H #include <sys/msg.h> #include <sys/types.h> #include <sys/ipc.h> #define MSG_PATH "./msg/msg" #define MSG_PJID 1818 #define MAX_MSG_LENGTH 256 typedef struct tag_msg { int length; char data[MAX_MSG_LENGTH]; } STRUCT_MSG_BUF; int message_init(); int message_receive(int msgid, STRUCT_MSG_BUF* pmsg, int flag); //int message_send(int msgid, const STRUCT_MSG_BUF* pmsg, int flag) int message_send(int msgid, const STRUCT_MSG_BUF* pmsg, int flag); #endif
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "game.h" #include "engine.h" #include "message.h" int gqid=0; void game_init() { //engine_init(); gqid=message_init(); } void game_start() { //engine_init(); game_send_msg(); game_receive_msg(); } int game_abort(char* msg) { engine_shut(); fprintf(stderr, "%s\n", msg); exit(EXIT_FAILURE); } // void game_over() { // print game over //engine_shut(); exit(EXIT_SUCCESS); } void game_send_msg() { char test[]="hello"; STRUCT_MSG_BUF msg={0}; memset(&msg, 0, sizeof(STRUCT_MSG_BUF)); msg.length=5; strncpy(msg.data, test, sizeof(test)); message_send(gqid, &msg, 0); } void game_receive_msg() { STRUCT_MSG_BUF msg={0}; memset(&msg, 0, sizeof(STRUCT_MSG_BUF)); message_receive(gqid, &msg, 0); }
相关文章推荐
- Activemq 消息发送、接收java代码实现队列模式
- 关于Posix消息队列简单的发送接收消息的练习
- 启动任务StartTask() 发送完消息队列 自己删除,接收方一直显示数据 用OSQFlush(Str_Q); //清空消息队列 下面纠结接收不到了 哈哈
- 一段同步接收和发送MQ消息的代码
- 消息队列的发送与接收.
- 一段同步接收和发送MQ消息的代码
- 一段同步接收和发送MQ消息的代码
- SpringBoot的RabbitMQ消息队列: 一、消息发送接收第一印象
- spring boot整合spring-kafka实现发送接收消息实例代码
- PHP发送队列消息接收队列消息
- POSIX消息队列 发送接收简单子
- MSMQ 消息队列 安装MSMQ 创建发送接收队例消息
- TeamTalk Android代码分析(业务流程篇)---消息发送和接收的整体逻辑说明
- IPC--消息队列 message queue(消息队列的创建,信息的发送和接收)
- 利用API发送和接收消息,本代码测试全通过
- ===注册时使用消息队列 发送邮件。遇到的【环境问题】总结。==比代码问题难找!!!
- C#操作MSMQ向本地消息队列发送和接收消息
- 消息队列发送数据和接收数据
- MSMQ消息通知系统之消息队列创建、发送、接收
- \t\tMSMQ 消息队列 安装MSMQ 创建发送接收队例消息