Re: Need another pair of eyes to figure this one out

From: Alwyn (dt015a1979_at_mac.com.invalid)
Date: 07/27/04


Date: Tue, 27 Jul 2004 08:37:26 +0100

In article <410570aa$1@usenet01.boi.hp.com>, Andrew Falanga
<falandr@hp.com> wrote:

> At one point, I'm opening a file descriptor and also opening a file that
> I want to write (in binary) to this descriptor. So that I can watch the
> progress of the write, I have embedded in the loop code to show how much
> is written and how much is left. Obviously, when completed the final
> write to stdout should be the files total size sent with 0 bytes
> remaining. However, that's not what I'm getting. So without further
> ado, here (in skeleton form) is what I have:

Well, what you have provided 'in skeleton form' is unproblematic, apart
from the mistake in the type of the size variables, which I noted
earlier. I've run your program successfully with a couple of files.
Though these files were much smaller than the one you used, I'm
convinced your program as it stands should work correctly for files of
less than 2 147 483 648 (two to the power of 31) bytes, given a 32-bit
int.

So the question arises: is the bug in the bit of the program you left
out? (That was the case a previous time you posted, as I recall.) Are
you taking account of the fact that the socket may not send all your
data in one go? Unless you are using a non-blocking technique, your
socket write procedure should look something like this:

int sendOnSocket(int mySocket, const void *myBuffer,
                              size_t bytesToWrite)
{
   size_t bytesWritten = 0;
   while (bytesWritten < bytesToWrite) {
      int bytesSent = send(mySocket, myBuffer, bytesToWrite, 0);
      if (bytesSent < 0) {
         perror("Socket send failed");
         return -1;
      }
      bytesWritten += bytesSent;
   }
   return 0;
}

HTH

Alwyn