栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在基于Linux的系统上,如何在交流程序中使用mqueue?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在基于Linux的系统上,如何在交流程序中使用mqueue?

下面是一个简单的服务器示例,该服务器从客户端接收消息,直到接收到“ exit”消息告诉其停止为止。

服务器 的代码:

#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;        attr.mq_flags = 0;    attr.mq_maxmsg = 10;    attr.mq_msgsize = MAX_SIZE;    attr.mq_curmsgs = 0;        mq = mq_open(QUEUE_NAME, O_CREAT | O_RDONLY, 0644, &attr);    CHECK((mqd_t)-1 != mq);    do {        ssize_t bytes_read;                bytes_read = mq_receive(mq, buffer, MAX_SIZE, NULL);        CHECK(bytes_read >= 0);        buffer[bytes_read] = '';        if (! strncmp(buffer, MSG_STOP, strlen(MSG_STOP)))        { must_stop = 1;        }        else        { printf("Received: %sn", buffer);        }    } while (!must_stop);        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];        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);                CHECK(0 <= mq_send(mq, buffer, MAX_SIZE, 0));    } while (strncmp(buffer, MSG_STOP, strlen(MSG_STOP)));        CHECK((mqd_t)-1 != mq_close(mq));    return 0;}

常见的 头:

#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 

编译

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/409917.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号