kimi写代码:writev_blocking

https://kimi.moonshot.cn/share/cqaca783r07f8tq3lheg

#include <sys/uio.h>
#include <unistd.h>
#include <errno.h>

// 调整iovec数组,使其指向未写入的数据部分
void adjust_iovec(struct iovec *iov, int *iovcnt, ssize_t bytes_written) {
    // 计算已经写入的字节数
    while (*iovcnt > 0 && bytes_written > 0) {
        if (bytes_written >= iov[0].iov_len) {
            bytes_written -= iov[0].iov_len;
            iov++;
            (*iovcnt)--;
        } else {
            iov[0].iov_base = (char *)iov[0].iov_base + bytes_written;
            iov[0].iov_len -= bytes_written;
            bytes_written = 0;
        }
    }
}

// 确保所有数据都被写入的writev封装函数
ssize_t blocking_writev(int fd, const struct iovec *iov, int iovcnt) {
    ssize_t bytes_written_total = 0;
    ssize_t bytes_written;
    struct iovec *local_iov = (struct iovec *)iov; // 使用本地副本进行修改
    int local_iovcnt = iovcnt;

    while (local_iovcnt > 0) {
        bytes_written = writev(fd, local_iov, local_iovcnt);
        if (bytes_written == -1) {
            if (errno == EINTR) { // 如果是中断错误,重试
                continue;
            } else {
                // 其他错误处理
                return -1;
            }
        }
        bytes_written_total += bytes_written;

        // 调整iovec数组以指向未写入的数据
        adjust_iovec(local_iov, &local_iovcnt, bytes_written);
    }

    return bytes_written_total;
}
posted @ 2024-07-15 14:44  joel-q  阅读(13)  评论(0编辑  收藏  举报