消息队列(1):windows10+eclipse+cygwin编写第一个消息队列程序

来源:互联网 发布:印第安人和亚洲人知乎 编辑:程序博客网 时间:2024/05/29 00:30

在windows10环境下安装了eclipse,cygwin,编写第一个简单的消息队列程序。

1.新建工程并配置编译器

在eclipse开发环境下新建一个C project,“Tool Chains”选择“cygwin GCC”
这里写图片描述
在工程右键点击属性,在“C/C++ build”下拉选项中“Tool Chain Editor”界面下的“current builder”下选择“CDT Internal Builder”。
如果Cygwin安装了make,则这里不选“CDT Internal Builder”也可以(默认为Gnu Make Builder)。
这里写图片描述

2.新建源文件并输入代码

新建一个c文件,输入源代码(附后)。

3.编译运行

运行结果,在控制台打印:
send pi is 3.141590.
msg size is 8192.
recv pi is 3.141590.
表示发送消息中的pi正确地赋给了接收消息结构体。
消息队列中各函数的用法后续再仔细摸。

附.源代码

#include <stdio.h>#include <stdlib.h>#include <mqueue.h>#include <fcntl.h>struct MsgType {    int len;    float pi;};int main() {    mqd_t msgq_id;    struct MsgType msg1;    struct MsgType msg2;    struct mq_attr msgq_attr;    unsigned int prio1 = 1;    unsigned int prio2;    const char *file = "/myposix";    msg1.len = 8;    msg1.pi = 3.14159;    msg2.len = 8;    msg2.pi = 0;    msgq_id = mq_open(file, O_RDWR | O_CREAT, S_IRWXU | S_IRWXG, NULL);    if (msgq_id == (mqd_t) -1) {        perror("mq_open error");        exit(1);    }    printf("send pi is %f.\n",msg1.pi);    if (mq_send(msgq_id, (char*) &msg1, sizeof(struct MsgType), prio1) == -1) {        perror("mq_send");        exit(1);    }    if (mq_getattr(msgq_id, &msgq_attr) == -1) {        perror("mq_getattr");        exit(1);    }    printf("msg size is %ld.\n",msgq_attr.mq_msgsize);    if (mq_receive(msgq_id, (char*) &msg2, msgq_attr.mq_msgsize, &prio2) == -1) {        perror("mq_receive");        exit(1);    }    printf("recv pi is %f.\n",msg2.pi);    if (mq_close(msgq_id) == -1) {        perror("mq_close");        exit(1);    }    if (mq_unlink(file) == -1) {        perror("mq_unlink");        exit(1);    }    return 0;}

[20170510]

0 0
原创粉丝点击