writen

programming/C_C++ 2012. 2. 22. 09:45
반응형


ssize_t writen(int fd, unsigned char *ptr, size_t nbytes)
{
  int nleft;
  ssize_t nwritten;

  nleft = nbytes;

  while (nleft > 0) {

    nwritten = write(fd, ptr, nleft);

    if (nwritten <= 0) {


      return (nwritten);        /* error */


    }

    nleft -= nwritten;
    ptr += nwritten;

  }

  return (nbytes - nleft);

}

 

 

 

ssize_t WriteN(int fd, const void * vptr, size_t n)
{
 size_t nleft;
 ssize_t nwritten;

 const char * ptr = (const char *)vptr;
 nleft = n;

 int tryCount = 0;

 while(nleft > 0)
 {
  /*if((nwritten = write(fd, ptr, nleft)) < 0)*/
  if((nwritten = send(fd, ptr, nleft, 0)) < 0)
  {
   int errorNum = errno;

   //fprintf(stderr, "WriteN Error [%d][%d]\n", errorNum, tryCount);

   if(errorNum == EINTR || errorNum == EAGAIN || errorNum == EWOULDBLOCK)
   {
    nwritten = 0;
    ++tryCount;
    //fprintf(stderr, "WriteN Error Ignore [%d][%d]\n", errorNum, tryCount);
   }
   else if(errorNum == ECONNRESET)
    return 0;
   else
    return -1;
  }
  else if(nwritten == 0)
  {
   return 0;
  }

  if( tryCount > 60)
  {
   fprintf( stderr, "WriteN Try Count Over !!!\n");
   return 0;
  }

  nleft -= nwritten;
  ptr += nwritten;
 }

 return n;
}

 

 

 

반응형
Posted by 공간사랑
,