练习代码,写个消息队列发送接收
#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); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· C# 模式匹配全解:原理、用法与易错点
· 记一次SSD性能瓶颈排查之路——寿命与性能之间的取舍
· 理解 .NET 结构体字段的内存布局
· .NET 9中的异常处理性能提升分析:为什么过去慢,未来快
· 字符集、编码的前世今生
· 记一次SSD性能瓶颈排查之路——寿命与性能之间的取舍
· 2025 年实用、全面的 VS Code 插件推荐!
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(五):使用.NET为树莓派
· dify打造数据可视化图表
· C# 模式匹配全解:原理、用法与易错点