gpt4 book ai didi

c - 读取 posix 消息队列时文件描述符错误

转载 作者:行者123 更新时间:2023-11-30 16:05:38 25 4
gpt4 key购买 nike

存在类似的线程,但没有一个有帮助。我在 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);
}

关于c - 读取 posix 消息队列时文件描述符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60225532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com