Question

I have two programs that send and receives messages back and forth from each other via IPC queues. However, sometimes the msgrcv function will get a blank message instead of receiving what was actually sent through the queue. I've commented out a fix that I think should work but I wanted to check here and see if this is the proper way to use msgrcv and msgsnd.

msgrcv:

int readqueue(int qid, long type, char *msg)
{
    int retval;

    // Current fix for blank messages
    /* strcpy(MsgQueue.Message, "");

    while (strcmp(MsgQueue.Message, "") == 0)
    {
        retval = msgrcv(qid, &MsgQueue, MSGSIZE, (long)type, 0);

        if (strcmp(MsgQueue.Message, "") == 0)
            printf("msgrcv fail\n");
    }*/

    retval = msgrcv(qid, &MsgQueue, MSGSIZE, (long)type, 0);
    strcpy(msg, MsgQueue.Message);

    return retval;
}



msgsnd:

int sendqueue(int qid, long type, char *msg)
{
    struct msqid_ds stat_buf, *pstat_buf;
    int av, retval;

    pstat_buf = &stat_buf;
    av = 0;

    /* Make sure there's space in the queue */
    do 
    {                
        retval = msgctl( qid, IPC_STAT, pstat_buf);
        if (retval == -1) 
        {
            fprintf(stderr, "msgctl in sendqueue failed!  Error = %d\n", errno);
            return retval;
        }
    } while ( pstat_buf->msg_qbytes - pstat_buf->msg_cbytes == 0);

    strcpy(MsgQueue.Message, msg);
    MsgQueue.MsgType = (long)type;

    retval = msgsnd(qid, &MsgQueue, MSGSIZE, 0);

    memset(MsgQueue.Message, '\0', MSGSIZE-1);
    return retval;
}
Was it helpful?

Solution

You say: "However, sometimes the msgrcv function will get a blank message instead of receiving what was actually sent through the queue"

I would suggest figuring out what is actually happening as the way to debug your problem.

msgrcv is going to return the number of bytes read or -1 on error ... you should check that and see what is actually going on.

If it's -1, errno gets set and there's a number of things that it can tell you. The man page lists them all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top