简体   繁体   English

使用C中的静态库将Stdout重定向(例如,重定向到文件)

[英]Stdout redirecting (to a file for instance) with a static library in C

I know already how to implement methods regarding usual freopen(), popen() or similar stdout/stdin/stderr -based redirecting mechanisms, but I wondered how should I apply the said mechanism to static (own) libraries in C? 我已经知道如何实现有关常规freopen(),popen()或类似的基于stdout / stdin / stderr的重定向机制的方法,但是我想知道如何将所述机制应用于C中的静态(自有)库? Say, I want to use a library to capture any program with printf() commands or so into a file (for instance) without letting it appear on the console - are there some things I need to acknowledge before applying simple fd dups and just calling the library in the main program? 说,我想使用一个库通过printf()命令等将任何程序捕获到一个文件中(例如),而又不使其出现在控制台上-在应用简单的fd dups并仅调用之前,我需要确认一些内容主程序中的库? Even piping seems to be complex seeing as execing here is risky... 甚至管道系统似乎也很复杂,因为执行此处存在风险。

thanks in advance. 提前致谢。

There's an old-timers' trick to force the entire process, regardless of what library the code comes from, to have one of the standard IO ports connected to a different filehandle. 不管代码来自哪个库,有一个老套的技巧可以迫使整个过程将标准IO端口之一连接到不同的文件句柄。 You simply close the filehandle in question, then open a new one. 您只需关闭有问题的文件句柄,然后打开一个新的文件句柄即可。 If you close(1), then open('some_file', 'w'), then ALL calls that would result in a write to stdout will go to some_file from that point forward. 如果先关闭(1),再打开('some_file','w'),则所有会导致对stdout进行写操作的调用将从该点开始进入some_file。

This works because open() always uses the first file descriptor that isn't currently in use. 之所以可行,是因为open()始终使用当前未使用的第一个文件描述符。 Presuming that you haven't closed stdin (fd=0), the call to open will get a file descriptor of 1. 假设您尚未关闭stdin(fd = 0),则调用open将获得文件描述符1。

There are some caveats. 有一些警告。 FILE outputs that haven't flushed their buffers will have undefined behavior, but you probably won't be doing this in the middle of execution. 尚未清空缓冲区的FILE输出将具有未定义的行为,但是您可能不会在执行过程中这样做。 Set it up as your process starts and you'll be golden. 在您的过程开始时进行设置,您会很高兴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM