我正在寻找一种在 C 中以编程方式(即,不使用命令行重定向)实现“tee”功能的方法,以便我的标准输出同时进入标准输出和日志文件。这需要适用于我的代码和输出到标准输出的所有链接库。有没有办法做到这一点?

最佳答案

你可以 popen() tee 程序。

或者你可以通过这样的子进程 fork() 和管道 stdout(改编自我写的一个真实的实时程序,所以它有效!):

void tee(const char* fname) {
    int pipe_fd[2];
    check(pipe(pipe_fd));
    const pid_t pid = fork();
    check(pid);
    if(!pid) { // our log child
        close(pipe_fd[1]); // Close unused write end
        FILE* logFile = fname? fopen(fname,"a"): NULL;
        if(fname && !logFile)
            fprintf(stderr,"cannot open log file \"%s\": %d (%s)\n",fname,errno,strerror(errno));
        char ch;
        while(read(pipe_fd[0],&ch,1) > 0) {
            //### any timestamp logic or whatever here
            putchar(ch);
            if(logFile)
                fputc(ch,logFile);
            if('\n'==ch) {
                fflush(stdout);
                if(logFile)
                    fflush(logFile);
            }
        }
        putchar('\n');
        close(pipe_fd[0]);
        if(logFile)
            fclose(logFile);
        exit(EXIT_SUCCESS);
    } else {
        close(pipe_fd[0]); // Close unused read end
        // redirect stdout and stderr
        dup2(pipe_fd[1],STDOUT_FILENO);
        dup2(pipe_fd[1],STDERR_FILENO);
        close(pipe_fd[1]);
    }
}

关于c - 如何在 C 中以编程方式实现 'tee'?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1761950/

10-13 08:13