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

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

问题描述

我想使用BUFF_SIZE 个字节填充的缓冲区/ write rel = nofollow>写入系统调用:

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()写入最多计数缓冲区中的字节将buf指向文件描述符fd引用的文件。

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

当然, actual的数量字节可以通过返回值来检测。但是,如果我想确保整个字节缓冲区都通过连接发送,什么是这样做的好方法?到目前为止,我一直在思考:

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

推荐答案

如果 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天全站免登陆