同时写入两个流 [英] Write simultaneousely to two streams
问题描述
有没有办法将两个流(或文件描述符)连接在一起,以便写入一个流也将写入第二个流? (C,Linux)
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)
谢谢。
推荐答案
用户laalto是正确,但在Linux上,您正在寻找的功能称为 fopencookie
。更正laalto的Linux示例导致:
User laalto is correct, but on Linux, the function you are looking for is called fopencookie
. Correcting laalto's example for Linux results in:
int my_writefn(void *cookie, const char *data, int n) {
FILE **files = (FILE **)cookie;
fwrite(data, n, 1, files[0]);
return fwrite(data, n, 1, files[1]);
}
int noop(void) { return 0; }
cookie_io_functions_t my_fns = {
(void*) noop,
(void*) my_writefn,
(void*) noop,
(void*) noop
};
FILE *files[2] = ...;
FILE *f = fopencookie((void *)files, "w", my_fns);
// ... use f as you like ...
当您写入 f
时,系统将执行 my_writefn
函数,并将传递给<$ c的数据传递给它$ C> fwrite的。为了简化操作,您可能还希望将文件流的缓冲更改为面向行:
When you write to f
, the system will execute your my_writefn
function passing it the data that was passed to fwrite
. To make things easier, you may also want to change the buffering for your file stream to be line oriented:
setvbuf(f, NULL, _IOLBF, 0);
这将缓冲传递给 fwrite的数据
直到输出换行符或从连接到进程的任何流中读取任何数据(例如stdin)。 注意:您必须在 fopencookie
之后但在将任何数据写入流之前调用 sevbuf
。
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 call sevbuf
after fopencookie
but before any data is written to the stream.
我使用行缓冲,因为我通常使用 fopencookie
将stderr重定向到syslog,或通过网络套接字,以及面向处理线的数据更容易,更有效。
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.
这篇关于同时写入两个流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!