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

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值