linux消息队列发送结构体

mq_common.h

#pragma once

const char * mqfile = "/mqtest";

struct TEST {
    int a;
    int b;
    char c;
    double d;
};

mq_service.cpp

#include 
#include 
#include 
#include 
#include 
#include "mq_common.h"
#include 
int main () {
    mqd_t mqd = mq_open (mqfile, O_CREAT | O_EXCL | O_WRONLY,  0600, NULL);

    /* Ensure the creation was successful */
    if (mqd == -1)
    {
        perror ("mq_open");
        exit (1);
    }

    int si = 0;
    int count = 0;
    while(count++ < 100) {
        TEST t;
        t.a = 1 + si++;
        t.b = 2 + si++;
        t.c = 'c';
        t.d = 0.5 + si++;
        std::cout << "msg count = " << count << ",a=" << t.a << ", b = " << t.b << ", c= " << t.c << ",d = " << t.d << std::endl;
        /* Send "HELLO" as a message with priority 10, then close the queue.
         *    Note the size is 6 to include the null byte '\0'. */
        mq_send (mqd, (const char *) &t, sizeof(TEST), 10);
    }
    auto rst = mq_close (mqd);
    std::cout << "mq_close result = " << rst << std::endl;
    auto unlinkrst = mq_unlink(mqfile);
    std::cout << "mq_unlink result = " << unlinkrst << std::endl;
    return 0;
}

mq_cleint.cpp

#include 
#include 
#include 
#include 
#include 
#include "mq_common.h"
#include 
int main() {
    /* Open the message queue for reading */
    mqd_t mqd = mq_open (mqfile, O_RDONLY);
    assert (mqd != -1);

    /* Get the message queue attributes */
    struct mq_attr attr;
    assert (mq_getattr (mqd, &attr) != -1);

    char *buffer = (char *)calloc (attr.mq_msgsize, 1);
    assert (buffer != NULL);

    int count = 0;
    while(count++ < 100) {
        /* Retrieve message from the queue and get its priority level */
        unsigned int priority = 0;
        if ((mq_receive (mqd, buffer, attr.mq_msgsize, &priority)) != -1) {
            TEST * msg = (TEST*)buffer;
            std::cout << "count = " << count << ",a = " << msg->a << ", b = " << msg->b << ", c = " << msg->c << ", d=" << msg->d << std::endl;
        }
    }
    /* Clean up the allocated memory and message queue */
    free (buffer);
    buffer = NULL;
    auto closerst =   mq_close (mqd);
    std::cout << "mq_close result = " << closerst << std::endl;
    return 0;
}

编译

g++ ./mq_service.cpp -o service --std=c++11 -lrt
g++ ./mq_client.cpp -o client --std=c++11 -lrt

你可能感兴趣的:(C++,linux,c++)