Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fread stalls on socket but fget doesnt?

Tags:

c

proxy

sockets

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?

like image 733
Matt Dean Avatar asked Oct 05 '22 13:10

Matt Dean


1 Answers

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.

like image 67
perreal Avatar answered Oct 10 '22 02:10

perreal