练习代码,写个消息队列发送接收

本文深入探讨了游戏开发中使用消息队列进行通信的技术细节,包括初始化、发送和接收消息的过程,以及关键参数的解释。通过具体代码示例展示了如何实现高效的跨进程通信,对于游戏开发者理解并应用消息队列技术提供了实用指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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);
}

 

转载于:https://www.cnblogs.com/unixshell/p/3341215.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值