How can I implement 'tee' programmatically in C?
Asked Answered
A

5

12

I'm looking for a way in C to programmatically (ie, not using redirection from the command line) implement 'tee' functionality such that my stdout goes to both stdout and a log file. This needs to work for both my code and all linked libraries that output to stdout. Any way to do this?

Allpurpose answered 19/11, 2009 at 9:20 Comment(1)
may I ask a more specific detail of why do you need such a solution? Is it to save on debugging..?Tankoos
E
7

You could popen() the tee program.

Or you can fork() and pipe stdout through a child process such as this (adapted from a real live program I wrote, so it works!):

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]);  
    }
}
Event answered 19/11, 2009 at 9:22 Comment(3)
+1 for not assuming anything (for instance, the above code is easily adapter to taking an already open file descriptor instead of a filename as argument)Lisette
tee("tee.txt"); system ("ftp"); --> doesnt seem to print stdin or stdout any idea?Phylloquinone
once i removed : if('\n'==ch) it prints. I guess it was waiting for \n. Now the tee function seems to be stuck unless I press enter at the end.Phylloquinone
J
6

The "popen() tee" answers were correct. Here is an example program that does exactly that:

#include "stdio.h"
#include "unistd.h"

int main (int argc, const char * argv[])
{
    printf("pre-tee\n");

    if(dup2(fileno(popen("tee out.txt", "w")), STDOUT_FILENO) < 0) {
        fprintf(stderr, "couldn't redirect output\n");
        return 1;
    }

    printf("post-tee\n");

    return 0;
}

Explanation:

popen() returns a FILE*, but dup2() expects a file descriptor (fd), so fileno() converts the FILE* to an fd. Then dup2(..., STDOUT_FILENO) says to replace stdout with the fd from popen().

Meaning, you spawn a child process (popen) that copies all its input to stdout and a file, then you port your stdout to that process.

Joerg answered 18/9, 2013 at 22:32 Comment(0)
F
2

You could use pipe(2) and dup2(2) to connect your standard out to a file descriptor you can read from. Then you can have a separate thread monitoring that file descriptor, writing everything it gets to a log file and the original stdout (saved avay to another filedescriptor by dup2 before connecting the pipe). But you would need a background thread.

Actually, I think the popen tee method suggested by vatine is probably simpler and safer (as long as you don't need to do anyhing extra with the log file, such as timestamping or encoding or something).

Facilitate answered 19/11, 2009 at 10:40 Comment(0)
G
1

You can use forkpty() with exec() to execute the monitored program with its parameters. forkpty() returns a file descriptor which is redirected to the programs stdin and stdout. Whatever is written to the file descriptor is the input of the program. Whatever is written by the program can be read from the file descriptor.

The second part is to read in a loop the program's output and write it to a file and also print it to stdout.

Example:

pid = forkpty(&fd, NULL, NULL, NULL);
if (pid<0)
    return -1;

if (!pid) /* Child */
{
execl("/bin/ping", "/bin/ping", "-c", "1", "-W", "1", "192.168.3.19", NULL);
}

/* Parent */
waitpid(pid, &status, 0);
return WEXITSTATUS(status);
Glove answered 19/11, 2009 at 9:28 Comment(1)
But this means running his program from another program doesn't it? Presumably he wants to avoid this otherwise he'd be willing to just use tee.Shalom
S
-2

There's no trivial way of doing this in C. I suspect the easiest would be to call popen(3), with tee as the command and the desired log file as an arument, then dup2(2) the file descriptor of the newly-opened FILE* onto fd 1.

But that looks kinda ugly and I must say that I have NOT tried this.

Shovelnose answered 19/11, 2009 at 9:26 Comment(2)
Tried this and causes race conditions. A problem can be that tee prints first sometimes.Maxinemaxiskirt
@Maxinemaxiskirt As I said, "untested and looks ugly". If you are using GNU libc, there's a functionality for creating your own FILE*-like objects and you could use that, but then you'd end up in unportability-land.Shovelnose

© 2022 - 2024 — McMap. All rights reserved.