检查msqid以查看是否有没有等待的消息或msgrcv

时间:2014-04-29 17:53:16

标签: c pthreads msg msgrcv

谢谢大家查看。

我想知道是否有办法检查消息队列(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;

据我所知,你可以无限期地等待,或者你可以在没有等待的情况下进行检查,如果没有任何问题就可以崩溃。我只是想在没有等待的情况下检查队列,然后继续。

您将获得的任何和所有帮助将不胜感激!非常感谢你!

1 个答案:

答案 0 :(得分:1)

你知道C没有"扔掉"什么? ENOMSG错误代码,而不是任何异常或信号。如果errno返回msgrcv,则使用-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");
}