检查msqid以查看是否存在未等待的消息或msgrcv
谢谢大家检查这个 我想知道是否有任何方法可以检查消息队列(msqid),并查看队列中是否有消息。如果没有,我想继续。我能在网上找到的唯一方法是使用msgrcv和IPC_NOWAIT,但是如果没有找到消息,就会抛出enomg。尽管没有消息,我还是想继续 我的代码太杂乱,我无法发布并感到自豪,因此我将发布一些我想要实现的伪代码:检查msqid以查看是否存在未等待的消息或msgrcv,c,pthreads,msg,msgrcv,C,Pthreads,Msg,Msgrcv,谢谢大家检查这个 我想知道是否有任何方法可以检查消息队列(msqid),并查看队列中是否有消息。如果没有,我想继续。我能在网上找到的唯一方法是使用msgrcv和IPC_NOWAIT,但是如果没有找到消息,就会抛出enomg。尽管没有消息,我还是想继续 我的代码太杂乱,我无法发布并感到自豪,因此我将发布一些我想要实现的伪代码: Main() { Initialize queues; Initialize threads // 4 clients and 1 server
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不会“抛出”任何东西吗?enomg
是错误代码,不是任何类型的异常或信号。如果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");
}
“…和崩溃…”msgrcv()
不会使程序崩溃。它将简单地返回-1
并将errno
设置为enomg
。