//队列线程来实现一个线程发消息,一个线程收消息
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include "string.h"
#include <mqueue.h>
static const char *mq_name = "/test_mq";//在/dev/mqueue下创建的文件名
static mqd_t mq_fd;//队列文件描述符 用来接受返回的消息
//第一个线程发消息
void *send_msg(void *arg)
{
// sleep(1);
printf("第一个线程发消息\n");
char *data = "hello world";
//mq_fd:消息队列文件描述符 data:发送的数据 strlen(data)+1:发送数据的长度 1:发送的优先级
mq_send(mq_fd, data, strlen(data)+1, 1);
return NULL;
}
//第二个线程收消息
void *recv_msg(void *arg)
{
sleep(1);
printf("第二个线程收消息\n");
char buf[1024];
//mq_fd:消息队列文件描述符 buf:接收的数据 sizeof(buf):接收数据的长度 0:接收的优先级
ssize_t len = mq_receive(mq_fd, buf, sizeof(buf), NULL);
printf("接收到的消息是:%s,长度是:%d\n", buf,len);
return NULL;
}
int main()
{
printf("主线程\n");
//创建消息队列
struct mq_attr attr;
attr.mq_maxmsg = 10;//队列中最多消息个数
attr.mq_msgsize = 100;//每个消息的最大字节数
//fd:消息队列文件描述符
//mq_name:消息队列文件名 attr:消息队列属性 O_RDWR | O_CREAT:读写权限
mq_fd = mq_open(mq_name, O_RDWR | O_CREAT, 0644, &attr);
if (mq_fd == -1)
{
printf("创建消息队列失败\n");
return -1;
}
//pt1:线程id NULL:线程属性 send_msg:线程函数 NULL:线程参数
pthread_t pt1, pt2;
//创建两个线程
pthread_create(&pt1, NULL, send_msg, NULL);
pthread_create(&pt2, NULL, recv_msg, NULL);
pthread_join(pt1, NULL);
pthread_join(pt2, NULL);
//关闭消息队列
mq_close(mq_fd);
mq_unlink(mq_name);
return 0;
}