fread stalls on socket but fget doesnt?

2019-06-22 04:01发布

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;
}

thanks!!

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

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

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?

标签: c sockets proxy
2条回答
贪生不怕死
2楼-- · 2019-06-22 04:44

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.

查看更多
做个烂人
3楼-- · 2019-06-22 04:50

Using fread() instead of recv() to read on a TCP socket seems strange to me..?

Anyway, fread is blocking as long as there is nothing to read. You should always check that a socket is ready to perform reading or writing, using select() for example on linux.

查看更多
登录 后发表回答