创建消息队列

comm.h

#ifndef __COMM_H__
#define __COMM_H__

#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<unistd.h>
#include<string.h>

#define PATHNAME  "./"
#define PROJ_ID 0x666

#define SIZE 128
#define SERVER_SIZE 1
#define CLIENT_SIZE 2

struct msgbuf
{
    long mtype;
    char mtext[SIZE];
};

int commMsgQueue(int flags);
int createMsgQueue();
int getMsgQueue();
int sendMSg(int msgid,long type,const char*_info);
int recMsg(int msgid,long type,char out[]);
int destroyMsgQueue(int msg_id);


#endif

comm.c

#include "comm.h"


int commMsgQueue(int flags)
{
    umask(0);
    key_t _k = ftok(PATHNAME,PROJ_ID);
    if(_k < 0)
    {
        perror("ftok");
        return -1;
    }
    int msg_id = msgget(_k,flags);
    if(msg_id < 0)
    {
       perror("msgget");
        return -2;
    }
    return msg_id;
}

int createMsgQueue()
{
    return commMsgQueue(IPC_CREAT|IPC_EXCL|0x666);
}

int getMsgQueue()
{
    return commMsgQueue(IPC_CREAT);
}

int sendMSg(int msgid,long type,const char*_info)
{
    struct msgbuf msg;
    msg.mtype = type;
    strcpy(msg.mtext,_info);
    if(msgsnd(msgid,&msg,sizeof(msg.mtext),0) < 0)
    {
        perror("msgsnd");
        return -1;
    }
    return 0;
}

int recMsg(int msgid,long type,char out[])
{
    struct msgbuf msg;
    if(msgrcv(msgid,&msg,sizeof(msg.mtext),type,0) < 0)
    {
        perror("msgrcv");
        return -1;
    }
    strcpy(out,msg.mtext);
    return 0;
}

int destroyMsgQueue(int msg_id)
{
    if(msgctl(msg_id,IPC_RMID,NULL) < 0)
    {
        perror("msgctl");
        return -1;
    }
    return 0;
}

server.c

#include"comm.h"
//#include"comm.c"

int main()
{
    int msgid = getMsgQueue(); 

    char buf[SIZE];
    while(1)
    {
        printf("please Enter$ ");
        fflush(stdout);
        size_t s = read(0,buf,sizeof(buf)-1);
        if(s > 0)
        {
            buf[s - 1] ='\0';
            sendMSg(msgid,CLIENT_SIZE,buf);
        }
        recMsg(msgid,SERVER_SIZE,buf);
        printf("server# %s\n ",buf);
    }
    return 0;
}

client.c

#include"comm.h"
#include"comm.c"

int main()
{
    int msgid = createMsgQueue();
    printf("msgid : %d\n",msgid);
    long type = SERVER_SIZE;
    char buf[SIZE];
    while(1)
    {
        recMsg(msgid,CLIENT_SIZE,buf);
        printf("client# %s\n",buf);
        printf("please Enter$ ");
        fflush(stdout);
        size_t s = read(0,buf,sizeof(buf));
        if(s > 0)
        {
            buf[s - 1] ='\0';
            sendMSg(msgid,SERVER_SIZE,buf);
        }
        sleep(1);
    }
    sleep(5);
    destroyMsgQueue(msgid);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值