您的位置:首页 > 运维架构 > Linux

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文档库中搜索相关关键字,有详细解释。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  socket linux splice 管道