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?

robottobor
  • 11,595
  • 11
  • 39
  • 37

5 Answers5

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]);  
    }
}
Will
  • 73,905
  • 40
  • 169
  • 246
  • +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) – Michael Apr 22 '15 at 23:31
  • tee("tee.txt"); system ("ftp"); --> doesnt seem to print stdin or stdout any idea? – Victor Oct 01 '16 at 23:33
  • 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. – Victor Oct 03 '16 at 17:22
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.

NHDaly
  • 7,390
  • 4
  • 40
  • 45
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).

Rasmus Kaj
  • 4,224
  • 1
  • 20
  • 23
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);
eyalm
  • 3,366
  • 19
  • 21
  • 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. – Benj Nov 19 '09 at 09:42
-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.

Vatine
  • 20,782
  • 4
  • 54
  • 70
  • Tried this and causes race conditions. A problem can be that tee prints first sometimes. – PALEN Jul 21 '13 at 21:05
  • @PALEN 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. – Vatine Jul 23 '13 at 09:35