[英]Linux : Check if message queue is empty
i want to know if a queue message is empty or not . 我想知道队列消息是否为空。 i have used msg_ctl() as follows it doesn't work :
我使用msg_ctl()如下,它不起作用:
struct msqid_ds buf;
int num_messages;
rc = msgctl(msqid, IPC_STAT, &buf);
and i've used this peek function : 我用过这个偷看功能:
int peek_message( int qid, long type )
{
int result, length;
if((result = msgrcv( qid, NULL, 0, type, IPC_NOWAIT)) == -1) {
if(errno==E2BIG)
return(1);
}
return(0);
}
in both cases i get the same result before and after sending a message to the queue. 在这两种情况下,我都会在向队列发送消息之前和之后得到相同的结果。
the message gets to the queue successfully , i've tested that with reading what i've sent. 消息成功进入队列,我已经通过阅读我发送的内容进行了测试。
I wrote the sample code that does seem to work properly: 我编写了似乎正常工作的示例代码:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <errno.h>
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[1]; /* message data */
};
int main(void) {
int msqid;
//msqid = msgget(IPC_PRIVATE, (IPC_CREAT | IPC_EXCL | 0600));
msqid = msgget((key_t)1235, 0600 | IPC_CREAT);
printf("Using message queue %d\n", msqid);
struct msqid_ds buf;
int rc = msgctl(msqid, IPC_STAT, &buf);
uint msg = (uint)(buf.msg_qnum);
printf("# messages before post: %u\n", msg);
printf("Posting message to queue...\n");
struct msgbuf qmsg;
qmsg.mtype = 100;
qmsg.mtext[0] = 'T';
int res = msgsnd(msqid, &qmsg, 1, MSG_NOERROR);
rc = msgctl(msqid, IPC_STAT, &buf);
msg = (uint)(buf.msg_qnum);
printf("# messages after post: %u\n", msg);
return 0;
}
Maybe that will be helpful to you? 也许这会对你有所帮助? The number of messages on the queue does seem to increment correctly when using this code.
使用此代码时,队列中的消息数似乎正确递增。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.