linux splice使用示例 (使用socket服务于单用户的回射服务器)
2016-03-12 16:03
746 查看
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <netinet/in.h>
#include<arpa/inet.h>
#include <fcntl.h>
#include <sys/stat.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 connfd = accept(listenfd, NULL, NULL);
int pipefd[2] = {0x00};
pipe(pipefd);
while(1)
{
splice(connfd, NULL, pipefd[1], NULL, 4096, SPLICE_F_MOVE | SPLICE_F_MORE);
splice(pipefd[0], NULL, connfd, NULL, 4096, SPLICE_F_MOVE | SPLICE_F_MORE);
}
close(listenfd);
return 0;
}
PS:pipe函数返回两个文件描述符,放置于数组中。其中第一个用来读取,第二个用来写入。
本篇仅用于演示splice的使用,(1)要使回射服务器能服务于多用户,可看本博客之前关于select的文章。(2)关于splice的原理,可以到 IBM develop work文档库中搜索相关关键字,有详细解释。
相关文章推荐
- java-模拟tomcat服务器
- Linux socket 初步
- Linux Kernel 4.0 RC5 发布!
- linux lsof详解
- linux 文件权限
- Linux 执行数学运算
- 10 篇对初学者和专家都有用的 Linux 命令教程
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)
- Linux 信号signal处理机制
- linux下mysql添加用户