我有一个带有许多工作线程的 C 应用程序。重要的是,这些不会阻塞,因此当工作线程需要写入磁盘上的文件时,我让它们写入内存中的循环缓冲区,然后有一个专用线程将该缓冲区写入磁盘。
工作线程不再阻塞。专用线程在写入磁盘时可以安全地阻塞,而不会影响工作线程(写入磁盘时它不持有锁)。我的内存缓冲区已调整为足够大,以便编写器线程可以跟上。
这一切都很好。我的问题是,如何为标准输出实现类似的东西?
我可以宏 printf() 写入内存缓冲区,但我无法控制可能写入标准输出的所有代码(其中一些位于第三方库中)。
想法?
尼克B
我喜欢使用的想法freopen
。您也许还可以重定向stdout
到管道使用dup http://mkssoftware.com/docs/man3/dup.3.asp and dup2 http://mkssoftware.com/docs/man3/dup2.3.asp,然后使用read
从管道中获取数据。
像这样:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_LEN 40
int main( int argc, char *argv[] ) {
char buffer[MAX_LEN+1] = {0};
int out_pipe[2];
int saved_stdout;
saved_stdout = dup(STDOUT_FILENO); /* save stdout for display later */
if( pipe(out_pipe) != 0 ) { /* make a pipe */
exit(1);
}
dup2(out_pipe[1], STDOUT_FILENO); /* redirect stdout to the pipe */
close(out_pipe[1]);
/* anything sent to printf should now go down the pipe */
printf("ceci n'est pas une pipe");
fflush(stdout);
read(out_pipe[0], buffer, MAX_LEN); /* read from pipe into buffer */
dup2(saved_stdout, STDOUT_FILENO); /* reconnect stdout for testing */
printf("read: %s\n", buffer);
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)