捕获程序输出
我正在制作一个小型库,它基本上将程序的标准输出(例如 printf())捕获到单独的进程/线程中...然后该进程应该执行某些任务(假设将这些捕获的输出写入文件) ...我刚刚开始认真进行 C 编程,所以我仍在学习。
我想知道执行此操作的最佳方法是什么,我的意思是使用进程或线程...我如何捕获这些 printf() 语句...此外,该库还必须处理由程序生成的任何子进程..一般假设是使用它的程序是线程程序,所以我可能应该采取哪种方法。
i am making a small library that will basically capture the standard outputs of a program (such as printf()) into a separate process/thread...this process should then perform certain tasks (lets say write these captured outputs to a file)...i am just beginning to do serious C programming so i am still learning.
i wanted to know what is the best way to do this, i mean using process or a thread...how do i capture these printf() statements...also this library must handle any child process if spawned by the programs...the general assumption is the program that uses it is a threaded one so may be what sort of approach should i take.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望您的程序或库启动程序并捕获其输出,请查看 popen(3)。它会给你一个 FILE 指针,你可以在其中读取程序的输出。
If you want your program or library to launch the program and capture its output, look at popen(3). It will give you a FILE pointer where you can read the output from the program.
从另一个程序捕获 STDOUT 的最简单方法是将其通过管道传输到程序的 STDIN(通过命令行“>”或“|”运算符)。所以基本上,在你的 C 库中,你应该只使用 scanf、gets 或任何你正在使用的 STDIN 函数读取 STDIN。
这是 Unix/Linux 世界中的一个相当标准的约定 - 程序以某种格式良好的方式从 STDIN 读取并写入 STDOUT,以便您可以通过简单地将管道添加到命令行来将不同的程序连接在一起,例如:
The easiest way to capture the STDOUT from another program is to simply pipe it into the STDIN of your program (via the command-line ">" or "|" operator). So basically, in your C library, you should just read from STDIN with scanf, or gets, or whatever STDIN function you're using.
This is a pretty standard convention in the Unix/Linux world - programs read from STDIN and write to STDOUT in some well-formatted way, so that you can pipeline different programs together by simply adding pipes to the command line, e.g.: