Is there a way to to couple two streams (or file descriptors) together so that writing to one stream will also write to the second one? (C, Linux)
Thanks.
Is there a way to to couple two streams (or file descriptors) together so that writing to one stream will also write to the second one? (C, Linux)
Thanks.
User laalto is correct, but on Linux, the function you are looking for is called
fopencookie
. Correcting laalto's example for Linux results in:When you write to
f
, the system will execute yourmy_writefn
function passing it the data that was passed tofwrite
. To make things easier, you may also want to change the buffering for your file stream to be line oriented:That will buffer up the data passed to
fwrite
until a newline is output or any data is read from any stream attached to the processes (e.g. stdin). NOTE: you must callsevbuf
afterfopencookie
but before any data is written to the stream.I use line buffering because I usually use
fopencookie
to redirect stderr to syslog, or over a network socket, and processing line oriented data is easier and more efficient.Use
funopen
orfwopen
and supply your own write function that writes to multipleFILE*
s.Example:
(Error handling omitted.)
Note that
funopen
andfwopen
are BSD and not in standard Linux. I'm not aware if there's a Linux-compatible equivalent.You can implement something similar to functionality of
tee
with boost::iostreams.Not sure if it's what you want, but 'tee' in unix does something similar.
The first thing that came to mind to me was also "tee". So, let's combine C and the shell with popen:
As a Unix bigot, I have assumed you are not trying this on Windows.