0

Thank you all for checking this.

I wanted to know if there is any way to check a message queue (msqid) and see if there are any messages in the queue. If not, I would like to continue. The only way I've been able to find online is by using msgrcv, with IPC_NOWAIT, but that throws ENOMSG if there is no message found. I would like to continue despite there being no message.

My code is too cluttered for me to post and feel proud of, so I'll post some pseudo-code of what I want to happen:

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;

As far as I can tell, you can either wait indefinitely, or you can check without waiting and crash if nothing's there. I just want to check the queue without waiting, and continue.

Any and all help you can give will be appreciated! Thank you very much!

user1660454
  • 61
  • 1
  • 6
  • "*... and crash ...*" `msgrcv()` won't crash the program. It would simly return `-1` and set `errno` to `ENOMSG`. – alk Apr 29 '14 at 18:00

1 Answers1

1

You know that C doesn't "throw" anything? The ENOMSG is en error code and not any kind of exception or signal. You check for it using errno if msgrcv returns -1.

You use it like this:

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");
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621