nuttx杂记

1、设置自启动应用

修改deconfig文件下的“CONFIG_INIT_ENTRYPOINT”参数即可

2、消息队列使用

以下是Nuttx系统中使用queue_create函数创建队列的示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <mqueue.h>

#define QUEUE_NAME "/my_queue"
#define MAX_MSG_SIZE 256
#define MSG_BUFFER_SIZE (MAX_MSG_SIZE + 10)


/*队列生成者*/
void *producer(void *arg)  
{
    mqd_t mq;
    char buffer[MSG_BUFFER_SIZE];

    mq = mq_open(QUEUE_NAME, O_WRONLY);

    if (mq == -1) {
        perror("mq_open");
        exit(1);
    }

    printf("Producer: Enter message to send, 'exit' to quit\n");

    while(1) {
        fgets(buffer, MSG_BUFFER_SIZE, stdin);

        if (strncmp(buffer, "exit", 4) == 0) {
            break;
        }

        if (mq_send(mq, buffer, strlen(buffer), 0) == -1) {
            perror("mq_send");
        }
    }

    mq_close(mq);
    return NULL;
}

/*队列消费者*/
void *consumer(void *arg)
{
    mqd_t mq;
    char buffer[MSG_BUFFER_SIZE];
    ssize_t bytes_read;

    mq = mq_open(QUEUE_NAME, O_RDONLY);

    if (mq == -1) {
        perror("mq_open");
        exit(1);
    }

    while(1) {
        bytes_read = mq_receive(mq, buffer, MSG_BUFFER_SIZE, NULL);

        if (bytes_read == -1) {
            perror("mq_receive");
            continue;
        }

        printf("Consumer: Received message: %s", buffer);
    }

    mq_close(mq);
    return NULL;
}

int main(int argc, char **argv)
{
    pthread_t prod_thread, cons_thread;
    struct mq_attr attr;
    attr.mq_flags = 0;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = MAX_MSG_SIZE;
    attr.mq_curmsgs = 0;

    mq_unlink(QUEUE_NAME);

    mqd_t mq = mq_open(QUEUE_NAME, O_CREAT | O_EXCL | O_RDONLY, 0666, &attr);

    if (mq == -1) {
        perror("mq_open");
        exit(1);
    }

    mq_close(mq);

    mq = mq_open(QUEUE_NAME, O_CREAT | O_EXCL | O_WRONLY, 0666, &attr);

    if (mq == -1) {
        perror("mq_open");
        exit(1);
    }

    pthread_create(&prod_thread, NULL, producer, NULL);
    pthread_create(&cons_thread, NULL, consumer, NULL);

    pthread_join(prod_thread, NULL);
    pthread_join(cons_thread, NULL);

    mq_close(mq);
    mq_unlink(QUEUE_NAME);

    return 0;
}


该示例代码创建了一个名为“my_queue”的消息队列,允许最多10个消息,每个消息的最大大小为256字节。它使用pthread库创建两个线程:一个生产者和一个消费者。生产者从标准输入读取消息并将其发送到消息队列中,而消费者从消息队列中读取消息并将其打印到标准输出中。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值