gpt4 book ai didi

c - 如何检查消息是否为空

转载 作者:行者123 更新时间:2023-11-30 18:11:44 24 4
gpt4 key购买 nike

所以我已经这样做了一整天了,但没有弄清楚。我需要检查是否有空消息传递到接收者或服务器,然后取消链接队列。这就是我所拥有的:

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));
}
}
}

最佳答案

来自 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。

我也强烈推荐您阅读this有关 POSIX 消息队列的有用教程。

这是一个工作示例:

#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;
}

关于c - 如何检查消息是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035792/

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