红联Linux门户
Linux帮助

关于 sendfile: Fast Data Transfers 的问题

发布时间:2010-09-16 11:01:34来源:红联作者:qiao16996814
#include
#include
#include
#include
#include
#include
#include
#include

int main (int argc, char* argv[])
{
int read_fd;
int write_fd;
struct stat stat_buf;
off_t offset = 0;
int byte = 0;

/* Open the input file. */
read_fd = open (argv[1], O_RDONLY);
/* Stat the input file to obtain its size. */
fstat (read_fd, &stat_buf);

printf("buffer size=%d\n",stat_buf.st_size);

/* Open the ouput file for writing, with the same permissions as the
source file. */
write_fd = open (argv[2], O_WRONLY | O_CREAT, stat_buf.st_mode);
/* Blast the bytes from one file to the other. */
byte = sendfile (write_fd, read_fd, &offset, stat_buf.st_size);

if (errno == EINVAL)
printf("errno=%d\n",errno);

printf("byte=%d\n",byte);
/* Close up. */
close (read_fd);
close (write_fd);

return 0;
}

==> 我先说我对sendfile的理解,sendfile就是可以省去中间buffer过渡,之解将文件复制。
上述程式,无非就是用只读方式打开一个文件,在用只写方式创建一个文件,在利用fstat得到源文件的大小,此大小留给sendfile用。

程式看上去没有问题,但是运行结果和预想的不一样,新创建的文件是空的,并没有将源文件的内容复制过来。
文章评论

共有 1 条评论

  1. deepwhite 于 2010-09-16 14:31:17发表:

    I've tried your codes, and it works well.