gpt4 book ai didi

c - 使用 write() 系统调用写一个完整的缓冲区

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:32 24 4
gpt4 key购买 nike

我想写一个充满 BUFF_SIZE 的缓冲区使用 write system call 在 TCP 套接字上传输字节:

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

documentation指出

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

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

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() 循环,直到 b 中的 s 字节被写入或者出现 fatal error 发生:

int writen(const int sd, const char * b, const size_t s, const int retry_on_interrupt)
{
size_t n = s;
while (0 < n)
{
ssize_t result = write(sd, b, n);
if (-1 == result)
{
if ((retry_on_interrupt && (errno == EINTR)) || (errno == EWOULDBLOCK) || (errno == EAGAIN))
{
continue;
}
else
{
break;
}
}

n -= result;
b += result;
}

return (0 < n) ?-1 :0;
}

这样调用它:

int retry_on_interrupt = ... /* {0|1} depending on wether a signal reception shall abort the write operation or not. */
int result = writen(fd, buff, sizeof(buf), retry_on_interrupt)
if (-1 == result)
{
perror("writen()");
}

关于c - 使用 write() 系统调用写一个完整的缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24259640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com