免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2125 | 回复: 0
打印 上一主题 下一主题

[C] sysv 消息队列 能否用select设置超时 ? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-03-25 22:30 |只看该作者 |倒序浏览
想实现一个获取一个消息的例子,功能大概是这样, 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 编辑 ]
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP