How can I implement 'tee' programmatically in C?

后端 未结 5 594
情深已故
情深已故 2020-12-04 01:38

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

5条回答
  •  既然无缘
    2020-12-04 01:51

    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).

提交回复
热议问题