所以我一直这样做了一整天而且没弄清楚。我需要检查是否将空消息传递给接收方或服务器,然后取消链接队列。 这就是我所拥有的:
while((c=getopt(argc, argv, ":q:"))!=-1){
switch(c){
case 'q':
q = 1;
Q = optarg;
break;
}
}
int oprimek_vrsta = -1;
char *msg = malloc(maxmsg_len + 1);
if(q != 0){
oprimek_vrsta = mq_open(Q, O_RDWR|O_CREAT|O_EXCL, 0660, &lastnosti_vrste);
if(oprimek_vrsta == -1){
perror("error creating queue");
return -1;
}
if(mq_getattr(oprimek_vrsta, &lastnosti_vrste) == -1){
perror("error reading attributes");
return -1;
}
while(loop){
memset(msg, 0, 4096);
munmap(msg, 4096);
msg_len = mq_receive(oprimek_vrsta, msg, maxmsg_len, &priority);
if(msg_len == -1){
perror("error reading message");
loop = 0;
free(msg);
mq_close(oprimek_vrsta);
mq_unlink(Q);
return -1;
}else{
write(1, msg, strlen(msg));
}
}
}
答案 0 :(得分:-1)
来自mq_receive手册:
mq_receive() removes the oldest message with the highest priority
from the message queue ... If the queue is empty, then, by default,
mq_receive() blocks until a message becomes available,
or the call is interrupted by a signal handler.
If the O_NONBLOCK flag is enabled for the message
queue description, then the call instead fails immediately with the error EAGAIN.
RETURN VALUE: On success, mq_receive() and mq_timedreceive() return the
number of bytes in the received message; on error, -1 is returned,
with errno set to indicate the error.
mq_receive的返回值不是您正在寻找的。您需要检查收到的消息长度是否为0。
我还非常建议您阅读有关POSIX消息队列的this有用教程。
这是一个有效的例子:
#include <stdio.h>
#include <mqueue.h>
#include <stdlib.h>
#include <string.h> /* memset */
#include <unistd.h> /* close */
#include <sys/mman.h>
#define QUEUE_NAME "/test"
#define MAX_MSG_LEN 100
int main(int argc, char **argv)
{
int q;
char* Q;
char c;
int loop = 1;
int msg_len;
struct mq_attr lastnosti_vrste;
lastnosti_vrste.mq_flags = 0;
lastnosti_vrste.mq_maxmsg = 10;
lastnosti_vrste.mq_msgsize = 100;
lastnosti_vrste.mq_curmsgs = 0;
while((c=getopt(argc, argv, "q:")) != -1)
{
switch(c)
{
case 'q':
mq_unlink(Q);
q = 1;
Q = QUEUE_NAME;
break;
}
}
int oprimek_vrsta = -1;
char *msg = malloc(MAX_MSG_LEN + 1);
if(q != 0)
{
oprimek_vrsta = mq_open(Q, O_RDWR|O_CREAT|O_EXCL, 0660, &lastnosti_vrste);
if(oprimek_vrsta == -1){
perror("error creating queue");
return -1;
}
if(mq_getattr(oprimek_vrsta, &lastnosti_vrste) == -1){
perror("error reading attributes");
return -1;
}
while(loop)
{
memset(msg, 0, 4096);
munmap(msg, 4096);
msg_len = mq_timedreceive(oprimek_vrsta, msg, MAX_MSG_LEN, 0);
if(strlen(msg) == 0)
{
perror("error reading message");
loop = 0;
mq_close(oprimek_vrsta);
mq_unlink(Q);
return -1;
}
else
{
write(1, msg, strlen(msg));
}
}
free(msg);
}
return 0;
}