Copy local file using sendfile, should I check sent bytes?

huangapple go评论59阅读模式
英文:

C - copy local file using sendfile, should I check sent bytes?

问题

我在Linux上使用sendfile复制文件。下面是我使用它的示例

struct stat statBuf;
fstat(fdFrom, &statBuf);
sendfile(fd, fdFrom, 0, statBuf.st_size);
close(fd);
close(fdFrom);

sendfile的文档说它可能不会一次写入所有字节。我使用的方式安全吗?或者我应该实现一个循环,在循环中检查sendfile的结果直到为0?

描述符来自本地文件。

在从源文件复制字节之前,目标文件应该被截断为零吗?

英文:

I copy file on linux with sendfile. Below is the example how I use it

struct stat statBuf;
fstat(fdFrom, &statBuf);
sendfile(fd, fdFrom, 0, statBuf.st_size);
close(fd);
close(fdFrom);

Documentation to sendfile says that it may not write all bytes at once. Is the way how I use it safe? Or I should implement loop in which I check result of sendfile until will be 0?

Descriptors are from local files.

Should be target file truncated to zero before copying bytes from source file?

答案1

得分: 4

Yes, you should loop and sum up the bytes transferred until you've sent all of them. It could look something like this:

ssize_t rv;
for (off_t tot = 0; tot != statBuf.st_size; tot += (off_t)rv) {
    rv = sendfile(fd, fdFrom, NULL, statBuf.st_size - tot);
    
    if (rv == -1) {
        // handle error
    }
}

If you want the target file to be an exact copy, then yes, open it with the O_TRUNC flag set - or call ftruncate(fd, statBuf.st_size); after the copying has been done just in case the previous content was larger than what you just copied.

英文:

Yes, you should loop and sum up the bytes transfered until you've sent all of them. It could look something like this:

ssize_t rv;
for(off_t tot = 0; tot != statBuf.st_size; tot += (off_t)rv) {
    rv = sendfile(fd, fdFrom, NULL, statBuf.st_size - tot);
    
    if(rv == -1) {
        // handle error
    }
}

> Should be target file truncated to zero before copying bytes from source file?

If you want the target file to be an exact copy, then yes, open it with the O_TRUNC flag set - or call ftruncate(fd, statBuf.st_size); after the copying has been done just in case the previous content was larger than what you just copied.

huangapple
  • 本文由 发表于 2023年5月15日 01:35:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76248859.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定