您的位置:首页 > 编程语言

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

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: