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? 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? Even piping seems to be complex seeing as execing here is risky...
我已经知道如何实现有关通常的freopen(),popen()或类似的基于stdout / stdin / stderr的重定向机制的方法,但我想知道如何将所述机制应用于C中的静态(自己的)库?比如说,我想使用一个库用printf()命令将任何程序捕获到一个文件中(例如)而不让它出现在控制台上 - 在应用简单的fd dup和调用之前,我需要确认一些事情吗?主程序中的库?即使是管道似乎很复杂,因为这里的施工风险很大......
thanks in advance.
提前致谢。
1 个解决方案
#1
2
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. 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.
无论代码来自哪个库,都有一个老式的强制措施来强制整个过程将一个标准IO端口连接到不同的文件句柄。您只需关闭有问题的文件句柄,然后打开一个新句柄。如果你关闭(1),然后打开('some_file','w'),那么导致写入stdout的所有调用将从那一点开始转到some_file。
This works because open() always uses the first file descriptor that isn't currently in use. Presuming that you haven't closed stdin (fd=0), the call to open will get a file descriptor of 1.
这是有效的,因为open()始终使用当前未使用的第一个文件描述符。假设您没有关闭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. Set it up as your process starts and you'll be golden.
有一些警告。未刷新缓冲区的FILE输出将具有未定义的行为,但您可能不会在执行过程中执行此操作。在你的过程开始时进行设置,你就会变得金黄。
#1
2
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. 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.
无论代码来自哪个库,都有一个老式的强制措施来强制整个过程将一个标准IO端口连接到不同的文件句柄。您只需关闭有问题的文件句柄,然后打开一个新句柄。如果你关闭(1),然后打开('some_file','w'),那么导致写入stdout的所有调用将从那一点开始转到some_file。
This works because open() always uses the first file descriptor that isn't currently in use. Presuming that you haven't closed stdin (fd=0), the call to open will get a file descriptor of 1.
这是有效的,因为open()始终使用当前未使用的第一个文件描述符。假设您没有关闭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. Set it up as your process starts and you'll be golden.
有一些警告。未刷新缓冲区的FILE输出将具有未定义的行为,但您可能不会在执行过程中执行此操作。在你的过程开始时进行设置,你就会变得金黄。