在 C 套接字编程中使用 C FILE 流

发布于 2024-10-07 20:21:23 字数 110 浏览 8 评论 0原文

我回来了一个关于在套接字编程中使用 C 文件流的问题。我正在阅读有关它的内容,看到了褒贬不一的评论 - 有些人说它不可靠(即抽象漏洞?)。

有人对在套接字编程中使用 C 文件流有什么看法吗?

Am back with a question on using C File stream in sockets programming. I was reading about it and saw mixed reviews - some people say it's not reliable (ie leaky abstraction?).

Has any one got a view about using C File stream in sockets programming?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心凉 2024-10-14 20:21:23

是的。不。

TCP 和 UDP 协议具有太多语义,无法轻松映射到常用的文件流 API。这并不是说这是不可能的,甚至是困难的,但可能会有很多很多的陷阱和边缘情况,这些会给你带来极其不可预测的行为。我也无法想到任何您可能希望将套接字视为普通文件的应用程序。

归根结底,一旦您处理了绑定、侦听和接受(您无法使用 C 文件流执行这些操作)并将生成的文件描述符包装在文件流类型中,您要做的就是使用fread() 和 fwrite(),也许是 fgetc(),所以您不妨将其保留为普通文件描述符并使用 receive() 和 send() 并省去包装的麻烦。您可能会省去处理缓冲的麻烦,但控制缓冲可以让您根据应用程序的要求调整缓冲区,并节省一些网络开销和速度。

Yes. Don't.

The TCP and UDP protocols have too many semantics to be easily mapped to your usual file stream APIs. That's not to say it's impossible or even difficult, but there are likely to be lots and lots of gotchas and edge cases that will give you wildly unpredictable behaviour. I also cannot think off the top of my head of any applications where you might want to treat a socket as an ordinary file.

At the end of the day, once you've dealt with binding and listening and accepting, none of which you can do with C File streams, and wrapped the resultant file descripter in a File stream type, all you are going to do is use fread() and fwrite(), maybe fgetc(), so you may as well leave it as an ordinary file descriptor and use recv(), and send() and save yourself the hassle of wrapping. You may save yourself the hassle of dealing with buffering, but having control of the buffering allows you to tune your buffer to the application's requirements and save yourself some network overhead and speed.

空名 2024-10-14 20:21:23

这取决于您正在编写的应用程序的类型。 FILE 流不适合非阻塞、异步或基于 select/poll 的 IO。对于执行连接到服务器、发出某些请求并获取结果的顺序任务的命令行程序来说,这可能不是问题。它也适用于仅从 inetd 运行的服务器进程。但是,如果您的应用程序将执行任何基于事件的操作,那么您就有麻烦了。如果您确实想在基于事件的应用程序中使用带有套接字的 FILE 流,则可以使用线程使其成为可能,但我怀疑这是一个好主意......

It depends on the kind of application you're writing. FILE streams are not suitable for nonblocking, asynchronous, or select/poll-based IO. This may be no problem for a command line program that performs a sequential task of connecting to a server, making some request, and getting the results. It also works alright for a run-from-inetd-only server process. But if your application will be doing anything event-based, you're in trouble. If you really want to use FILE streams with sockets in an event-based application, you can make it possible using threads, but I doubt it's a good idea...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文