C, sendfile() and send() difference?

后端 未结 3 2052
孤独总比滥情好
孤独总比滥情好 2021-01-31 11:07

sendfile() copies data between two file descripters within kernel space. Somewhere I saw if you are writing a web server in C in linux you should use send() and recv() instead o

3条回答
  •  没有蜡笔的小新
    2021-01-31 11:34

    If fd is a socket file descriptor, then these system calls are identical:

    • send(fd, data, length, 0) is the same as write(fd, data, length)
    • recv(fd, data, length, 0) is the same as read(fd, data, length)

    So, unless you need to set a non-zero flags parameter, it makes no difference whether you use send/recv or write/read.

    The sendfile system call is an optimization. If you have a socket sockfd and a regular file filefd and you want to copy some file data to the socket (e.g. if you're a web server serving up a file), then you might write it like this:

    // Error checking omitted for expository purposes
    while(not done)
    {
        char buffer[BUFSIZE];
        int n = read(filefd, buffer, BUFSIZE);
        send(sockfd, buffer, n, 0);
    }
    

    However, this is inefficient: this involves the kernel copying the file data into userspace (in the read call) and then copying the same data back into kernel space (in the send call).

    The sendfile system call lets us skip all of that copying and have the kernel directly read the file data and send it on the socket in one fell swoop:

    sendfile(sockfd, filefd, NULL, BUFSIZE);
    

提交回复
热议问题