本文介绍了C,发送文件()和send()的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内核空间内的两个文件之间descripters的sendfile()复制数据。某处我看到,如果你是在Linux编写一个Web服务器用C,你应该使用send()和recv()而不是使用write()和read()。那么,在send()使用内核空间呢?

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 of using write() and read(). So is the send() use the kernel space as well?

不管我用来发送 - 发送文件()或发送() - 上我将使用recv的客户端()右

Whatever I use for sending - sendfile() or send() - on the client side I'll be using recv() right?

在另一面,表示:发送的唯一区别()和write(2 )为标志的presence。以零标志参数,发送()等同于写(2)。

On the flip side, man page says: "The only difference between send() and write(2) is the presence of flags. With a zero flags argument, send() is equivalent to write(2)."

推荐答案

如果 FD 是一个套接字文件描述符,那么这些系统调用是相同的:

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


  • 发(FD,数据长度,0)相同写(FD,数据长度)

  • 的recv(FD,数据长度,0)相同阅读(FD,数据长度)

  • 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)

所以,除非你需要设置一个非零标记参数,它使没有区别是否使用发送/ recv的写/读

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

发送文件系统调用是一个优化。如果你有一个插座的sockfd 和普通文件 filefd 并要一些文件中的数据复制到插座(例如:如果你提供一个文件的Web服务器),那么你可能会写这样的:

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);

这篇关于C,发送文件()和send()的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 18:48