With sendfile (), is it possible to specify when in_fd is in EOF?

Reading the Linux sendfile system call page, I wonder if it is possible for the caller to know when in_fd is in EOF. Presumably, this may be signaled by a return value of 0, but this leads to the question of what the actual value of 0 means. If the sendfile is like write , then the return value of 0 simply means that 0 bytes were copied. But if sendfile is like read , then a return value of 0 will mean EOF. Should someone know in advance how many bytes must be copied from in_fd to out_fd in order to use sendfile ? What does it mean when sendfile returns 0?

+4
source share
4 answers

I donโ€™t think there is any direct way to find out, but it doesnโ€™t really matter. You can usually find the size of the input file via stat/fstat and use this to calculate your transfer. The end connector will not matter to you.

The only situation that should be problematic is if you want to transfer a file that is growing or shrinking. Given that the input file must be mmap-ed, and the bad things that can happen (without any smart code) with mmap in these situations, you probably just shouldn't use sendfile for these cases.

+4
source

you can use the offset parameter to count the read.

According to the Man page

If the offset is not NULL, it points to a variable containing the file offset from which sendfile () will start reading data from in_fd. When sendfile () returns, this variable will be set to a byte offset after the last byte that was read. If offset is not NULL, then sendfile () does not change the current file offset in_fd; otherwise, the current file offset is adjusted to display the number of bytes read from in_fd.

count - the number of bytes to copy between file descriptors.

RETURN VALUE If the transfer is successful, the number of bytes written to out_fd is returned. On error, -1 is returned, and errno is set accordingly.

and yes, which means that a return value of 0 means that there is no data copied for the socket entry.

+3
source

You can assume that EOF is reached when the number of bytes sent is 0:

 sent = sendfile(out_fd, in_fd, &offset, nbytes); if (sent == 0) { // EOF ... } 

This assumption also works with non-blocking sockets.

0
source

in my case, when faced with a file, we trim rsync, the application uses sendfile to transfer the file at the same time. I find that the application consumes 100% CPU in state, I correct my code by referring to the next article, the question disappears. http://www.linuxjournal.com/article/6345

dot uses F_SETLEASE to get file rentals for your application.

0
source

All Articles