System V消息队列实现进程间通信

本文介绍了如何使用System V消息队列在C++中实现进程间的高效通信,包括关键函数如msgget、msgsnd和msgrcv的应用,以及msgQueue类的创建、操作和销毁过程。通过实例展示了创建消息队列、发送和接收消息的基本步骤。

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

System V消息队列实现进程间通信

#ifndef __12_MSG_HPP__
#define __12_MSG_HPP__

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

const int BUFSIZE = 1024;
const int PROJECT_ID = 0x1234;
const char *pathname = "./";

inline int error(const char *errstr)
{
    printf("%s\n", errstr);
    return -1;
}

class msgQueue
{
private:
    int msqid;
    std::unordered_map<const char *, int> stat;
    int _getmsq(int msqflg)
    {
        int _msqid;
        if ((_msqid = msgget(ftok(pathname, PROJECT_ID), msqflg)) < 0)
            error("msgget");
        
        return _msqid;
    }
public:
    msgQueue();
    ~msgQueue();
    int open(const char *st);
    void send(int msqid, char *msg);
    char *recv(int msqid);
    void destroymsgQueue();
};

msgQueue::msgQueue()
{
    msqid = -1;
    stat.insert(std::make_pair("c", IPC_CREAT | IPC_EXCL | 0666));
    stat.insert(std::make_pair("r", S_IRUSR));
    stat.insert(std::make_pair("w", S_IWUSR));
}

msgQueue::~msgQueue()
{}

int msgQueue::open(const char *st)
{
    msqid = _getmsq(stat[st]);
    return msqid;
}

void msgQueue::send(int _msqid, char *msg)
{
    if (msgsnd(_msqid, msg, strlen(msg) + 1, 0) < 0)
        error("msgsnd");
}

char *msgQueue::recv(int _msqid)
{
    char *buffer = (char *)malloc(sizeof(char) * BUFSIZE);
    if (msgrcv(_msqid, buffer, BUFSIZE, 0L, 0) < 0)
        error("msgrcv");
    return buffer;
}

void msgQueue::destroymsgQueue()
{
    if (msqid == -1)
        return;

    if (msgctl(msqid, IPC_RMID, NULL) < 0)
        error("msgctl");
}

#endif

server

#include "12-msg.hpp"

int main(int argc, char *argv[])
{
    msgQueue msq;
    msq.open("c");
    msq.send(msq.open("w"), (char *)"LPLPLPLPLPLP");
    sleep(20);
    msq.destroymsgQueue();
    return 0;
}

client

#include "12-msg.hpp"

int main(int argc, char *argv[])
{
    msgQueue msq;
    printf("%s\n", msq.recv(msq.open("r")));
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值