c - 如何在基于 Linux 的系统上的 c 程序中使用 mqueue?

如何在基于 Linux 的系统上的 c 程序中使用 mqueue(消息队列)?

我正在寻找一些好的代码示例,这些示例可以展示如何以正确和适当的方式完成此操作,也许是一个操作指南。

最佳答案

以下是一个简单的服务器示例,它接收来自客户端的消息,直到它收到一条“退出”消息告诉它停止。

服务器的代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <mqueue.h>

#include "common.h"

int main(int argc, char **argv)
{
    mqd_t mq;
    struct mq_attr attr;
    char buffer[MAX_SIZE + 1];
    int must_stop = 0;

    /* initialize the queue attributes */
    attr.mq_flags = 0;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = MAX_SIZE;
    attr.mq_curmsgs = 0;

    /* create the message queue */
    mq = mq_open(QUEUE_NAME, O_CREAT | O_RDONLY, 0644, &attr);
    CHECK((mqd_t)-1 != mq);

    do {
        ssize_t bytes_read;

        /* receive the message */
        bytes_read = mq_receive(mq, buffer, MAX_SIZE, NULL);
        CHECK(bytes_read >= 0);

        buffer[bytes_read] = '\0';
        if (! strncmp(buffer, MSG_STOP, strlen(MSG_STOP)))
        {
            must_stop = 1;
        }
        else
        {
            printf("Received: %s\n", buffer);
        }
    } while (!must_stop);

    /* cleanup */
    CHECK((mqd_t)-1 != mq_close(mq));
    CHECK((mqd_t)-1 != mq_unlink(QUEUE_NAME));

    return 0;
}

客户端的代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <mqueue.h>

#include "common.h"


int main(int argc, char **argv)
{
    mqd_t mq;
    char buffer[MAX_SIZE];

    /* open the mail queue */
    mq = mq_open(QUEUE_NAME, O_WRONLY);
    CHECK((mqd_t)-1 != mq);


    printf("Send to server (enter \"exit\" to stop it):\n");

    do {
        printf("> ");
        fflush(stdout);

        memset(buffer, 0, MAX_SIZE);
        fgets(buffer, MAX_SIZE, stdin);

        /* send the message */
        CHECK(0 <= mq_send(mq, buffer, MAX_SIZE, 0));

    } while (strncmp(buffer, MSG_STOP, strlen(MSG_STOP)));

    /* cleanup */
    CHECK((mqd_t)-1 != mq_close(mq));

    return 0;
}

通用 header :

#ifndef COMMON_H_
#define COMMON_H_

#define QUEUE_NAME  "/test_queue"
#define MAX_SIZE    1024
#define MSG_STOP    "exit"

#define CHECK(x) \
    do { \
        if (!(x)) { \
            fprintf(stderr, "%s:%d: ", __func__, __LINE__); \
            perror(#x); \
            exit(-1); \
        } \
    } while (0) \


#endif /* #ifndef COMMON_H_ */

编译:

gcc -o server server.c -lrt
gcc -o client client.c -lrt

https://stackoverflow.com/questions/3056307/

相关文章:

linux - Linux 中的直接内存访问

c++ - Linux C++ : how to profile time wasted due t

python - 编译 python 时 --enable-optimizations 做了什么?

php - 如何为 php 启用 mysqlnd?

node.js - Ansible 将以什么用户身份运行我的命令?

linux - 使用非 root 用户帐户安装 Git

regex - shell脚本中 "=~"运算符的含义

linux - 如何删除 Mercurial 存储库

linux - 自动化 Amazon EBS 快照 任何人在 linux 上都有一个好的脚本或解决方

linux - 如果我们想在版本化的源代码中搜索,使用 git grep 比使用普通 grep 更好