存在类似的线程,但是它们都没有帮助。在Linux下阅读以下代码时,我得到了错误的文件描述符错误。在声明O_CREAT标志时,我还会指定队列属性。任何想法?谢谢。
#include <stdio.h>
#include <mqueue.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#define Log(...) printf(__VA_ARGS__); fflush(stdout)
int error;
void* producer(void* arg) {
Log("producer\n");
mqd_t q = mq_open("/ytm", O_RDWR);
mq_send(q, "kardeshians", sizeof("kardeshians"), 1);
}
void* consumer(void* arg) {
Log("consumer\n");
char buff[32];
mqd_t q = mq_open("/ytm", O_RDONLY);
int prio;
while(1) {
error = mq_receive(q,buff,sizeof(buff), NULL);
if(error) {
printf("read error %d %s\n", errno, strerror(errno));
}
}
}
int main() {
struct mq_attr attr;
attr.mq_maxmsg = 10;
attr.mq_msgsize = 32;
mqd_t queue = mq_open("/ytm", O_CREAT | O_RDWR, 0, &attr);
pthread_t tid;
pthread_create(&tid, 0 , producer, 0);
pthread_create(&tid, 0 , consumer, 0);
while(1);
}
问题同时在于执行许可权和消息大小。以root用户身份运行并使读取缓冲区的大小大于mq_msgsize后,它可以工作。感谢您提供错误检查建议。这是工作代码:
#include <stdio.h>
#include <mqueue.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#define Log(...) printf(__VA_ARGS__); fflush(stdout)
int error;
void* producer(void* arg) {
Log("producer\n");
mqd_t q = mq_open("/ytm", O_RDWR);
if(q == -1) {
printf("mq_open error %d %s\n", errno, strerror(errno));
exit(0);
}
while(1) {
int retval = mq_send(q, "kardeshians\n", sizeof("kardeshians\n"), 1);
if(retval == -1) {
printf("mq_open error %d %s\n", errno, strerror(errno));
exit(0);
}
}
}
void* consumer(void* arg) {
Log("consumer\n");
char buff[64];
mqd_t q = mq_open("/ytm", O_RDONLY);
int prio;
while(1) {
int retval = mq_receive(q,buff,sizeof(buff), NULL);
if(retval == -1) {
printf("read error %d %s\n", errno, strerror(errno));
} else {
printf("got message : %s", buff);
}
}
}
int main() {
struct mq_attr attr;
attr.mq_maxmsg = 10;
attr.mq_msgsize = 32;
mq_unlink ("/ytm");
mqd_t queue = mq_open("/ytm", O_CREAT | O_RDWR, 0, &attr);
pthread_t tid;
pthread_create(&tid, 0 , producer, 0);
pthread_create(&tid, 0 , consumer, 0);
while(1);
}