linux splice使用示例 (使用socket服务于单用户的回射服务器)

来源:互联网 发布:数据安全保护策略 编辑:程序博客网 时间:2024/06/07 02:30
#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文档库中搜索相关关键字,有详细解释。

0 0
原创粉丝点击