如何禁用fread()中的缓冲? [英] How do I disable buffering in fread()?

查看:101
本文介绍了如何禁用fread()中的缓冲?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用fread()和fwrite()读写套接字.我相信这些功能用于缓冲输入和输出.有什么方法可以在仍然使用这些功能的同时禁用缓冲吗?

I am reading and writing to sockets using fread() and fwrite(). These functions, I believe are for buffered input and output. Is there some way that I can disable buffering while still using these functions ?

我正在构建一个远程桌面应用程序,并且远程客户端似乎滞后于服务器",我不知道可能是什么原因...我认为可能是由于缓冲读取和写..但使用setvbuf无效.

I am building a remote desktop application and the remote client seems to be "lagging a bit behind the server", and I dont have any idea what may be the reason... I thought it may be because of buffered read and write .. but using setvbuf didnt work.

滞后"是指远程桌面客户端在服务器后面运行几秒钟.在大约15到20秒的延迟后,服务器在特定时刻的操作会反映在客户端.

By "lagging", I mean that the remote desktop client is running a few seconds behind the server. What the server is doing at a particular moment is reflected on the client side after a delay of some 15-20 seconds.

此外,我不想不使用fread(),因为它是现有代码的一部分.我不想修改它.我最终可以使用write()和read(),但我想避免使用它.

Also, I dont want to not-use-fread(), because it is a part of existing code. I don't want to modify it. I could eventually use write() and read(), but I would like to avoid it.

推荐答案

您可以使用setvbuf禁用对特定文件指针的缓冲:

You can use setvbuf to disable buffering for a specific file pointer:

setvbuf(fp, NULL, _IONBF, 0);

编辑

正如史蒂文斯(Stevens)所警告的,

使用标准输入来混合套接字有点麻烦.这里有一些报价.

EDIT

Mixing sockets with standard input is kind of tricky, as warned by Stevens. Here are a few quotes.

后三个功能[fseek,fsetpos,rewing]的问题是 他们都叫lseek,在套接字上失败.

The problem problem with these latter three functions [fseek, fsetpos, rewing] is that they all call lseek, which fails on a socket.

处理此读写问题的最简单方法是打开两个 给定套接字的标准I/O流:一个用于读取,一个用于 写作.

The easiest way to handle this read-write problem is to open two standard I/O streams for a given socket: one for reading and one for writing.

解决此[缓冲问题]的一种方法是强制输出流 通过调用setvbuf进行行缓冲.另一个是强迫每个 在每次调用fput之后调用fflush来输出回显的行. 但实际上,这两种解决方案中的仍然容易出错,并且 可能与Nagle算法交互不良

One way around this [buffering problem] is to force the output stream to be line buffered by calling setvbuf. Another is to force each echoed line to be output by calling fflush after each call to fputs. But in practice, either of these solutions is still error-prone and may interact badly with the Nagle algorithm


结论:


In conclusion:

尝试停止使用stdio. 使用stdiofreadfwrite 没有任何意义.请直接使用readwrite.史蒂文斯(Stevens)说行缓冲"输出,因为人们将fgetsfputs与stdio一起使用

Try to stop using stdio. It makes no sense to use stdio and fread and fwrite. Use straight read and write instead. Stevens speaks of "line buffered" output because people use fgets and fputs with stdio

这篇关于如何禁用fread()中的缓冲?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆