问题描述
我正在尝试写入我的消息队列 (mq_send)。
这是我首先打开队列然后写入队列的代码。
开幕:
int MQconnect (mqd_t * mq,char * name)
{
//printf("hello from MQconnect\n");
do{
mq=mq_open(name,O_WRONLY); //O_RDONLY
}while(mq==-1);
if(mq== -1){
return 0;
}
else
return 1;
// Connects to an existing mailslot for writing Uses mq as reference pointer,so that you can reach the handle from anywhere/
// Should return 1 on success and 0 on fail*/
}
写作:
int MQwrite (mqd_t mq,void * sendBuffer) // (const char) sendBuffer
{
int nrOfBytes = mq_send(mq,(const char)sendBuffer,1024,10);
printf("\n%d",nrOfBytes);
return nrOfBytes; //nrOfBytes;
// Write a msg to a mailslot,return nr Uses mq as reference pointer,so that you can reach the handle from anywhere
// should return number of bytes read */
}
打开工作正常,但我无法写入消息队列。
mq_send 返回 -1 作为返回值,错误信息为:
errno 的值:9 perror 打印的错误:文件描述符错误 错误:错误的文件描述符
void * mqClient(void * arg){
pthread_mutex_lock(&mutex);
char answer[20];
mqd_t mq_on_server;
usleep(1000);
int response = MQconnect(&mq_on_server,"/servermq");
if(response==0){
printf("something went wrong with MQconnect\n");
}
else{
//This loop continously scans planets given by the user
//while(!(0)){
printf("\nWrite to mailBox: ");
scanf("%s",answer);
MQwrite (mq_on_server,&answer);
int c;
while ( (c = getchar()) != '\n' && c != EOF);
//fflush(stdout);
//}
}
pthread_mutex_unlock(&mutex);
}
有人知道为什么我会收到这种错误吗?我的朋友有完全相同的代码,对他来说它正在工作。
解决方法
您忘记取消引用 MQconnect
中的给定指针。
int MQconnect (mqd_t * mq,char * name)
{
//printf("hello from MQconnect\n");
#if 0
/* wrong part */
do{
mq=mq_open(name,O_WRONLY); //O_RDONLY
}while(mq==-1);
if(mq== -1){
#else
/* fixed code */
do{
*mq=mq_open(name,O_WRONLY); //O_RDONLY
}while(*mq==-1);
if(*mq== -1){
#endif
return 0;
}
else
return 1;
// Connects to an existing mailslot for writing Uses mq as reference pointer,so that you can reach the handle from anywhere/
// Should return 1 on success and 0 on fail*/
}