2022-4-16 使用tee函数同时将数据输出到文件和屏幕当中

测试程序

#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<assert.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/sendfile.h>
int main(void){
    
    
    int filefd = open("abc.txt",O_CREAT|O_WRONLY|O_TRUNC,0666);
    if(filefd == -1){
    
    
        perror("open");
        exit(-1);
    }
    int pipefd_stdout[2];
    int ret = pipe(pipefd_stdout);
    if(ret == -1){
    
    
        perror("pipe");
        exit(-1);
    }
    int pipefd_file[2];
    ret = pipe(pipefd_file);
    if(ret == -1){
    
    
        perror("pipe");
        exit(-1);
    }
    ret = splice(STDIN_FILENO,NULL,pipefd_stdout[1],NULL,32768,SPLICE_F_MOVE|SPLICE_F_MORE);
    if(ret == -1){
    
    
        perror("splice1");
        return -1;
    }
    ret = tee(pipefd_stdout[0],pipefd_file[1],32768,SPLICE_F_NONBLOCK);
    if(ret == -1){
    
    
        perror("tee");
        return -1;
    }
    ret = splice(pipefd_file[0],NULL,filefd,NULL,32768,SPLICE_F_MOVE|SPLICE_F_MORE);
    if(ret == -1){
    
    
        perror("splice");
        return -1;
    }
    ret = splice(pipefd_stdout[0],NULL,STDOUT_FILENO,NULL,32768,SPLICE_F_MOVE|SPLICE_F_MORE);
    if(ret == -1){
    
    
        perror("splice");
        return -1;
    }
    close(filefd);
    return 0;
    close(pipefd_file[0]);
    close(pipefd_file[1]);
    close(pipefd_stdout[0]);
    close(pipefd_stdout[1]);
    return 0;
}

运行结果
在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_51187533/article/details/124215741