- 论坛徽章:
- 0
|
想实现一个获取一个消息的例子,功能大概是这样, msg_post 往消息队列send 一个msg, 在另外一个线程中,读该消息队列,如果如果在限定的时间内, 消息队列描述符可读,则返回该消息,否则, 超时返回,但实际上,我发现, 这样做,总是超时返回. 不晓得是何缘故? 难道这样实现本身就错了?
以下是源代码
struct MSGqueue_t *msg_get ( )
{
struct timeval tv;
fd_set rset;
int ret;
struct msgbuf buf;
struct MSGqueue_t *msg;
try_select:
tv.tv_sec = 5;
tv.tv_usec = 0;
FD_ZERO(&rset);
FD_SET(msgfd, &rset);
if ((ret = select (msgfd + 1, &rset, NULL, NULL, &tv) ) < 0)
{
if (errno == EINTR) goto try_select;
else return NULL;
}
else if (ret == 0) return NULL;
if (msgrcv(msgfd, &buf, sizeof (struct msgbuf), 0, IPC_NOWAIT) < 0)
{
logfile (LOG_PRINT, "[%s,%d]recv msg failed, err = %s\n",
__FILE__, __LINE__, strerror (errno) );
return NULL;
}
msg = (struct MSGqueue_t *) malloc (sizeof (struct MSGqueue_t) );
if (!msg)
{
logfile (LOG_PRINT, "[%s,%d]alloc mem failed\n",
__FILE__, __LINE__ );
return NULL;
}
memset(msg, 0, sizeof(struct MSGqueue_t));
memcpy(msg, buf.mtext, sizeof(struct MSGqueue_t));
return msg;
}
|
亟盼大侠帮忙.
[ 本帖最后由 gczh1006 于 2008-3-25 23:18 编辑 ] |
|