只需一个操作即可写入两个文件描述符 [英] Writing to two file descriptors by only one operation
问题描述
我想在C中实现日志记录功能,并将消息记录到stdout和某些文件中. 我想写一些类似fprintf(logout,"msg");的东西.用某种方式声明了FILE *注销,它将把字符串重定向到stdout和某些文件.是否有可能?
I want to implement logging functionality in C and log messages to both stdout and some file. I would like to write something like fprintf(logout, "msg"); with somehow declared FILE* logout which will redirect strings to both stdout and some file. Is it possible?
推荐答案
您显然想要一个类似FILE
的对象,该对象将其写入重定向到两个基础FILE
(stdout
和日志文件).标准C不允许以任何方式对FILE
对象进行子类化",因此在C中是不可能的.但是,
You apparently want a FILE
-like object that redirects its writes to two underlying FILE
s (stdout
and the log file). Standard C doesn't allow "subclassing" FILE
objects in any way, so this is not possible in C. However, GNU libc does, so if your program is Linux-only, you can do that with some programming. As this is extremely non-portable, it is strongly recommended against.
一种更可移植的方法是通过写入管道并创建从管道读取并写入两个基础文件的进程或线程.例如,假设POSIX:
A more portable way to achieve this is by writing to a pipe and creating a process or thread that reads from the pipe and writes to both underlying files. For example, assuming POSIX:
FILE *tee_file(FILE *fp1, FILE *fp2)
{
int fds[2];
if (pipe(fds))
return NULL;
switch (fork()) {
case 0: {
char buf[512];
int nread;
FILE *r = fdopen(fds[0], "r");
close(fds[1]);
while ((nread = fread(buf, 1, sizeof buf, r)) {
fwrite(buf, 1, nread, fp1);
fwrite(buf, 1, nread, fp2);
}
_exit(0);
}
case -1:
return NULL;
}
close(fds[0]);
return fdopen(fds[1], "w");
}
/* after calling "fp = tee_file(fp1, fp2)", writes to fp
end up in fp1 and fp2. */
这两种方法都会给您的程序增加很多复杂性,这应该有充分的理由.您想要的是使用一个日志记录框架,该框架允许写入多个输出(它们全部都可以写入),或者按照H2CO3的答案所述编写自己的记录.
Both approach add a good deal of complication to your program which should be justified by a very good reason. What you want is to use a logging framework that allows writing to multiple outputs (they all do), or write your own as outlined by H2CO3's answer.
这篇关于只需一个操作即可写入两个文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!