Writing a program’s stdout to a file and stdout in Linux
I want to pipe stdout of a program to both a file to store the output of the program and to the console in order to be able to observe the progress of the program. Unfortunatelly bash does not allow splitting pipes out of the box. So I just hacked this little program in order to accomplish that. It is quite simple - all it does is take stdin and write it to stdout and stderr. That way one can be piped to a file and the other will be appearing on the console.
splitstdin.c:
- #include <stdio.h>
- #define BUF_LEN 255
- main(int argc, char** argv)
- {
- size_t numRead;
- char buf[BUF_LEN + 1];
- size_t charSize = sizeof(char);
- while (!feof(stdin)) {
- numRead = fread(buf, charSize, BUF_LEN, stdin);
- buf[numRead] = '\0'; /* append a nul character */
- fwrite(buf, charSize, numRead, stdout);
- fwrite(buf, charSize, numRead, stderr);
- }
- }
For stdout AND stderr of the program "programtoobserve" to get parsed by splitstdin use this commandform in bash:
split to file and console:
programtoobserve 2>&1 | splitstdin 2>backupOutput
split to two files:
programtoobserve 2>&1 | splitstdin 1>backupOutput1 2>backupOutput2
Edit:
I found the proper built-in command: tee

BTW, you don’t need to append the null to the buffer,
fwrite(3)doesn’t read any more than numRead characters anyway. You would if, for some reason, you were trying tofprintf(3)it.Comment on November 23, 2007 @ 05:12:00
Hey Paul,
thanks for the heads up. You are absolutely right. I guess what I did there is probably called defensive programming. It’s like a reflex: C + char[] -> nul terminate that damn thing.
Cheers,
Tobi
Comment on November 23, 2007 @ 11:19:03
With ksh you can run the following and have
the file in /tmp and also see in the console
./testprogram 2>&1 | tee /tmp/filename
Comment on December 12, 2007 @ 18:31:27
Thank you for this, it’s very useful.
Comment on June 6, 2008 @ 15:19:05