int FdOutStream::writeWithTimeout(const void* data, int length, int timeoutms)
{
  int n;

  do {
    fd_set fds;
    struct timeval tv;
    struct timeval* tvp = &tv;

    if (timeoutms != -1) {
      tv.tv_sec = timeoutms / 1000;
      tv.tv_usec = (timeoutms % 1000) * 1000;
    } else {
      tvp = NULL;
    }

    FD_ZERO(&fds);
    FD_SET(fd, &fds);
    n = select(fd+1, 0, &fds, 0, tvp);
  } while (n < 0 && errno == EINTR);

  if (n < 0)
    throw SystemException("select", errno);

  if (n == 0)
    return 0;

  do {
    // select only guarantees that you can write SO_SNDLOWAT without
    // blocking, which is normally 1. Use MSG_DONTWAIT to avoid
    // blocking, when possible.
#ifndef MSG_DONTWAIT
    n = ::send(fd, (const char*)data, length, 0);
#else
    n = ::send(fd, (const char*)data, length, MSG_DONTWAIT);
#endif
  } while (n < 0 && (errno == EINTR));

  if (n < 0)
    throw SystemException("write", errno);

  gettimeofday(&lastWrite, NULL);

  return n;
}
The software writes data past the end, or before the beginning, of the intended buffer.