- 論壇徽章:
- 0
|
想實現(xiàn)一個獲取一個消息的例子,功能大概是這樣, msg_post 往消息隊列send 一個msg, 在另外一個線程中,讀該消息隊列,如果如果在限定的時間內(nèi), 消息隊列描述符可讀,則返回該消息,否則, 超時返回,但實際上,我發(fā)現(xiàn), 這樣做,總是超時返回. 不曉得是何緣故? 難道這樣實現(xiàn)本身就錯了?
以下是源代碼
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 編輯 ] |
|