0

谢谢大家检查这个。

我想知道是否有任何方法可以检查消息队列(msqid)并查看队列中是否有任何消息。如果没有,我想继续。我能够在网上找到的唯一方法是使用带有 IPC_NOWAIT 的 msgrcv,但如果没有找到消息,则会抛出 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;

据我所知,您可以无限期地等待,也可以在没有等待的情况下进行检查,如果没有任何内容,则崩溃。我只想检查队列而不等待,然后继续。

您可以提供的任何和所有帮助将不胜感激!非常感谢!

4

1 回答 1

1

你知道 C 不会“抛出”任何东西吗?这ENOMSG错误代码,而不是任何类型的异常或信号。errno您使用if msgrcvreturns来检查它-1

你像这样使用它:

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");
}
于 2014-04-29T18:00:28.830 回答