How to get a file using sendfile?

sending a file with a send file is easy:

stat(fd,&filestat);
sendfile(sockfd,fd,0,filestat.len)

but how to get the file using sendfile? since I don't know the file length, should I send the file length first?

 sendfile(fd, sockfd,0, ??)

There seem to be two ways to do this:

  • send filestat.len file first

    //send end
    write(sockfd,filestat.len);
    sendfile(sockfd,fd,&offset,filestat.len);
    //receive end
    read(sockfd,&len);
    sendfile(fd,sockfd,&offset,len)
    
  • use the loop at the end of the reception:

    //receive end
    while(sendfile(fd,sockfd,&offset,BUF_LEN) > 0) {
        offset += BUF_LEN;
    }
    

Which one is better? Should I handle the length of the buffer specifically? Is there a problem in the first case when the file is quite large?

(I really like the mac os sendfile version, it will send to the end of the file if count is 0)

+4
source share
3 answers

This is a great question!

: read() recv() ( ?), 0, (EOF).

! , . , , , () .. - , .

( . , ?)

. , , , . ( , .)

( ) , , , .

!

+4

sendfile():

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

, read() : , , . , -1 0.

+1

If you are a socket on the receiving end of a send file, it is no different from any other TCP connection. When you reach eof, yours will readeither receivereturn 0 bytes. If there is a socket connection that precedes and deletes the data from the send file, then yes, you need some kind of consistent protocol so that each side can understand what they are sending and receiving.

0
source

All Articles