本例中,sendfile的作用是从文件描述符复制数据到socket中。因为它的“零拷贝”特性,使得它特别适用于HTTP服务器,FTP服务器程序。#include <sys/types.h>#include <sys/socket.h>#include <stdio.h>#include <netinet/in.h>#include <fcntl.h>#include <sys/stat.h>#include <sys/sendfile.h>void check(int res, const char *fucname){if(res < 0)
{perror(fucname);}}int main()
{int res;
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in local;
local.sin_family = AF_INET;local.sin_addr.s_addr = htonl(INADDR_ANY);local.sin_port = htons(5000);res = bind(listenfd, (struct sockaddr *)&local, sizeof(local));check(res, "bind");
res = listen(listenfd, 3);check(res, "listen");
int conn = accept(listenfd, NULL, NULL);
int datafd = open("log", O_RDONLY);struct stat file_info;
fstat(datafd, &file_info);int data_size = file_info.st_size;
sendfile(conn, datafd, NULL, data_size);return 0;
}
linux sendfile示例
最新推荐文章于 2024-06-25 11:39:01 发布