我有两个程序通过 IPC 队列来回发送和接收消息。但是,有时 msgrcv 函数会收到一条空白消息,而不是接收实际通过队列发送的消息。我已经注释掉了一个我认为应该有效的修复程序,但我想在这里检查一下,看看这是否是使用 msgrcv 和 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;
}
消息:
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;
}