感谢大家检查此内容。
我想知道是否有任何方法可以检查消息队列(msqid)并查看队列中是否有任何消息。如果没有,我想继续。我能够在线查找的唯一方法是使用 msgrcv 和 IPC_NOWAIT,但是如果没有找到消息,则会抛出 ENOMSG。尽管没有任何消息,我仍想继续。
我的代码太困惑,无法发布并感到自豪,所以我将发布一些我想要发生的伪代码:
Main()
{
Initialize queues;
Initialize threads // 4 clients and 1 server
pthread_exit(NULL);
}
Server()
{
while (1)
{
check release queue; // Don't want to wait
if ( release )
increase available;
else
// Do nothing and continue
Check backup queue; // Don't want to wait
if ( backup)
read backup;
else
read from primary queue; // Will wait for message
if ( readMessage.count > available )
send message to backup queue;
else
send message to client with resources;
decrease available;
} //Exit the loop
}
Client
{
while(1)
{
Create a message;
Send message to server, requesting an int;
Wait for message;
// Do some stuff
Send message back to server, releasing int;
} // Exit the loop
}
typedef struct {
long to;
long from;
int count;
} request;
据我所知,您可以无限期地等待,也可以不等待而进行检查,如果没有任何内容,则崩溃。我只想检查队列而不等待,然后继续。
我们将不胜感激您所能提供的任何帮助!非常感谢!
最佳答案
你知道 C 不会“抛出”任何东西吗? ENOMSG
是一个错误代码,而不是任何类型的异常或信号。如果 msgrcv
返回 -1
,则使用 errno
检查它。
你可以像这样使用它:
if (msgrcv(..., IPC_NOWAIT) == -1)
{
/* Possible error */
if (errno == ENOMSG)
{
printf("No message in the queue\n");
}
else
{
printf("Error receiving message: %s\n", strerror(errno));
}
}
else
{
printf("Received a message\n");
}
关于检查一个 msqid 看看是否有消息 without waiting 或 msgrcv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23371855/