开发者社区 问答 正文

epoll的EPOLLOUT事件

文档上说epoll监听的描述符可写的时候会触发EPOLLOUT事件,

可是我想知道在接受到EPOLLOUT后,调用write还有限制吗,比如write过大的数据会不会还是返回EAGAIN。

想像这样的场景
服务器收到客户端的请求,要获取一张图片。
服务器读取该图片,保存为字节数组(char*)
然后调用write欲将数据写入套接字,却返回EAGAIN
epoll_ctl为套接字添加EPOLLOUT的事件监听
那么问题来了,当EPOLLOUT事件发生时,往该套接字写该图片的数据,是否能成功
服务器使用C语言开发。不过我想其他语言的epoll都是从C语言绑定过去的,原理应该一样。

这里有点要注意的是,第一次write失败是因为数据量太大,如果write数据少一点是可以成功的。(至少从经验看是如此)那么当EPOLLOUT触发时能保证write一张大图片的数据会成功吗。

展开
收起
a123456678 2016-06-21 10:49:13 3075 分享 版权
1 条回答
写回答
取消 提交回答
  • /*
     * Packs up the buf and write to socket in non-blocking way
     * If all data is writen, return 1
     * If only part of data is writen, return 0, to be continue next time
     * If error occurs, return -1
     * 
     * Note, if j_socket_write() returns 0, then you can call it with NULL in buf next time, until all data is writen
     */
    int j_socket_write(JSocket * jsock, const void *buf, guint32 count)
    {
        guint32 size = j_socket_wdata_length(jsock);
        if (size == 0) {
            /* new data to write */
            if (buf == NULL) {
                return 1;           /* no data? must be a mistake */
            }
            gchar *len = pack_length4(count);
            j_socket_wdata_append(jsock, len, 4);
            j_socket_wdata_append(jsock, buf, count);
            g_free(len);
            size = j_socket_wdata_length(jsock);
        }
    
        gint n;
        count = size>4096?4096:size;
    
        while(size>0){  /* writes segmentation */
            n = j_socket_write_raw(jsock, j_socket_wdata(jsock), count);
            if(n<0){
                if(errno==EAGAIN){
                    return 0;
                }
                return -1;  /* It's a real error */
            }
            j_socket_wdata_pop(jsock,n);
            size = j_socket_wdata_length(jsock);
            count = size>4096?4096:size;
        }
        return 1;
    }
    2019-07-17 19:44:36
    赞同 展开评论
问答分类:
问答地址: