Thread: blocked on read/recv / how to read/send proper buffers

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    14

    Question blocked on read/recv / how to read/send proper buffers

    hello forum,

    i am somehow stuck with a beginner networking problem. i generally do not know how to read/recv all data to process it. for instance, taking this example:

    Code:
    file = open("test.txt",O_RDONLY);
    while(read(file,buf,1)>=0){
           strncat(store,buf,1);
    }
    now, if i would replace the strncat line with
    Code:
    send(client,buf,1,0);
    the while loop finishes and the program ends like it should. with the strncat in place it reads the file but is somehow stuck in the while loop. i wonder what i do wrong there.
    possibly i have generally a wrong way of trying to read a buffer with recv/read wrong, possibly somebody can show me what the correct way is to read/send a full buffer. lets say
    i have a defined buffer of 1024 bytes but the file is 4094 big.

    thank for your answers,
    fc

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > read(file,buf,1)>=0
    Have you thought about RTFM - On success, the number of bytes read is returned (zero indicates end of file)

    Unless you have
    Code:
    char buf[2] = { 0, 0 };
    your strncat is a disaster waiting to happen.
    In any event, it is an UGLY way of solving the problem.

    Code:
    char buf[BUFSIZ];
    while ( (r=read(file,buf,BUFSIZ)) > 0 ) { // read until EOF or error
      char *bp = buf;
      do {
        w = send(client,buf,r,0);
        if ( w <= 0 ) break;
        r -= w;  // reduce the amount left to send
        buf += w;  // what remains to be sent
      } while ( r > 0 ); // keep going until it's all sent
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed