fread 在套接字上停顿但 fget 没有? [英] fread stalls on socket but fget doesnt?

查看:91
本文介绍了fread 在套接字上停顿但 fget 没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 c 语言开发代理服务器.我已经在不同的地方使用 fread 和 fgets 的组合,但想要调和并理解差异.在以下示例中,我尝试在我之前成功使用 fget 的地方使用 fread.相反,我的服务器现在挂在 fread 线上.有什么区别?为什么我的程序挂了?

I'm working on a proxy server in c. I've gotten rather far using a combination of fread and fgets in different places but would like to reconcile and understand the difference. In the following example, I'm trying to use fread in a place i previously used fget successfully. Instead my server now hangs at the fread line. What's the difference and why is my program hanging?

void HandleTCPClient(int clntSocket)
{
    FILE *request = fdopen(clntSocket, "r");
    char reader[2000];
    size_t q; //typo before
    while((q=fread(reader, 1, sizeof(reader), request))>0) {  //hangs here!
        printf("i read something!\n");
    }
    return;
}

谢谢!!

所以如果我写了一行 "while((q=fread(reader, 1, 1, request))>0) {"

so if i make the line "while((q=fread(reader, 1, 1, request))>0) {"

我的屏幕上到处都是我读了一些东西"...

i get "i read something" all over my screen...

不确定这是什么意思.那么,如果流中至少没有您的缓冲区大小的字符数,那么 fread 真的什么都不做是正确的吗?

not sure what this means. So is it correct that fread will literally do nothing if there isn't at least your buffer's size number of characters present in the stream?

推荐答案

fgets 在读取换行符时返回,而 fread 将阻塞直到请求的字节数可用流或 EOF.在您的情况下,调用会阻塞,因为您没有在流中准备好 2000 字节的数据.

fgets returns when a newline is read while fread will block until requested number of bytes are available in the stream or on EOF. In your case, the call blocks because you do not have 2000 bytes of data ready in the stream.

这篇关于fread 在套接字上停顿但 fget 没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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