使用 write() 系统调用写入一个完整的缓冲区 [英] Writing a full buffer using write() system call

查看:30
本文介绍了使用 write() 系统调用写入一个完整的缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 编写系统调用:

I want to write a buffer filled with BUFF_SIZE bytes over a TCP socket using the write system call:

#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);

文档指出

write() 将最多 count 个字节从指向 buf 的缓冲区写入文件描述符 fd 所引用的文件.

write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd.

当然,可以通过返回值检测实际写入的字节数.但是,如果我想确保我的整个字节缓冲区都通过连接发送,那么这样做的好方法是什么?到目前为止,我在想:

Of course, the number of actual bytes written can be detected by the return value. However, if I want to ensure that my whole buffer of bytes gets sent over the connection, what would be a good way to do this? So far, I was thinking:

while ( (ch = fgetc(pipe) ) != EOF )
{
    buff[ 0 ] = ch;
    bytes_in_buff++;

    // fill a buffer's worth of data from the pipe
    for (int i = 1; i < BUFF_SIZE; ++i, ++bytes_in_buff)
    {
        if ( (ch = fgetc(pipe) ) == EOF)
            break;

        buff[ i ] = ch;
    }

    // write that buffer to the pipe
    int bytes_sent = 0;
    while (bytes_sent < BUFF_SIZE)
    {
        bytes_sent = write(fd, buff, bytes_in_buff);
    }
}

但当然,如果我每次都继续发送整个缓冲区 bytes_sent <;BUFF_SIZE .

But of course, some redundant bytes will be sent if I continue to send the entire buffer each time bytes_sent < BUFF_SIZE .

推荐答案

如果 write() 返回小于 BUFF_SIZE 您建议的循环将永远不会终止;并且您需要检查错误.

If write() returns less than BUFF_SIZE your suggested loop will never terminate; and you need to check for errors.

你需要这样的东西:

while (bytes_in_buff > 0)
{
    bytes_sent = write(fd, buff, bytes_in_buff);
    if (bytes_sent < 0)
    {
        perror("write");  // or whatever
        break;
    }
    buff += bytes_sent;
    bytes_in_buff -= bytes_sent;
}

然而这个问题在几年前在 news:comp.protocols.tcp-ip 上深入讨论,这是 TCP/IP 实现者闲逛的地方,并同意在阻塞模式下,write()send() 必须在返回之前发送整个缓冲区.

However this issue was discussed in extenso on news:comp.protocols.tcp-ip some years ago, which is the place where TCP/IP implementators hang out, and it was agreed there that, in blocking mode, both write() and send() must send the entire buffer before returning.

这篇关于使用 write() 系统调用写入一个完整的缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆