如何将 fprintf 输出重定向到 C 套接字?
如何将 fprintf
输出重定向到套接字?
我正在编辑有很多 fprintf
调用的源代码。它记录到一个文件中。但我想将此日志重定向到套接字。
这怎么能做到呢?
How can I redirect fprintf
output to a socket?
I am editing source code which has a lot of fprintf
calls. It logs to a file. But I would like to redirect this log to a socket.
How can this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在类 Unix 系统上,打开套接字(获取文件描述符)。
将套接字映射到
stderr
如果您尚未使用
stderr
,您可以简单地使用dup2()
将套接字设置为输出通道。即使您已将一些数据发送到原始stderr
,您也可以执行此操作。评论中关于使用 fflush() 的建议可能是相关的,尽管 stderr 通常是无缓冲的而不是完全缓冲的(因此通常没有任何需要刷新的内容)。freopen()
函数可用于更改流的输出,例如stderr
(特别是)。嗯,您可以使用 freopen() 来将 stderr 映射到 /dev/fd/N ,其中 N 是套接字的文件描述符?是的,你可能可以。将套接字映射到其他流
重新阅读您的问题 - 我在其中没有看到
stderr
。因此,fdopen()
函数从文件描述符创建一个流。因此,如果您可以指定要写入的日志记录的流,那么您就可以了。如果您无法指定它但可以看到它,那么上面的freopen()
技巧在这里也应该起作用。On Unix-like systems, open the socket (getting a file descriptor).
Map socket to
stderr
If you've not yet used
stderr
, you can simply usedup2()
to make the socket into the output channel. You may be able to do that even if you have sent some data to the originalstderr
. The suggestion in the comment about usingfflush()
may be relevant, thoughstderr
is usually unbuffered rather than fully buffered (so there is not usually anything to flush).The
freopen()
function can be used to change the output of a stream such asstderr
(in particular). Hmmm, could you usefreopen()
to mapstderr
to/dev/fd/N
where N is the file descriptor of the socket? Yes, you probably could.Map socket to other stream
Re-reading your question - I don't see
stderr
in it. So thefdopen()
function creates a stream from a file descriptor. So if you can specify the stream for the logging to write to, you're home. If you can't specify it but can see it, then thefreopen()
trick above should work here too.不存在“C 套接字”这样的东西,但您可能指的是两个东西之一(WinSock 或 libsocket)。不管怎样,我使用的基本方法是使用 #define 和一个简单的函数,类似于:
这将在任何一个中工作,除了 libsocket 之外,您应该 typedef 或使用 int 作为 SOCKET 。
确保在完成套接字登录后
#undef fprintf
!There is no such thing as a "C socket" but you are probably referring to one of two things (WinSock or libsocket). Either way, the basic method I'd use would be to use a
#define
and a simple function, similar to this:That will work in either, except with libsocket you should typedef or use int for SOCKET.
Make sure you
#undef fprintf
after you're done logging to the socket!我意识到这不是你的问题,但你可能会考虑使用像 netcat 这样的工具,而不是弄乱代码(这看起来不是一个微不足道的改变)。
您可以执行以下操作(更新为使用日志 fifo):
http://netcat.sourceforge.net/
I realize this isn't your question, but you might consider using a tool like netcat instead of messing with the code (which doesn't seem like a trivial change).
You can do something like this (updated to use a log fifo):
http://netcat.sourceforge.net/