READN Writen realizes linux socket buffer read-write __linux

Source: Internet
Author: User
Tags socket

Turn from: http://blog.csdn.net/yanook/article/details/6587542


The read write operation on the socket differs from the normal file IO operation, and the number of bytes read write on the socket may be less than required, but this is not an error because the socket buffer may have reached its limit. All that is needed is to call read Write again to write or output the remaining characters. This is common in sockets, but occurs only when the socket is not plugged in while writing a throttle socket, but we always invoke the writen and READN functions instead of read and write for the purposes of prevention, in case of returning insufficient character values.

The following is the READN, writen function Source:

ssize_t/* Read "n" bytes from a descriptor. */
READN (int fd, void *vptr, size_t N)
{
size_t Nleft;
ssize_t nread;
Char *ptr;

ptr = vptr;
Nleft = n;
while (Nleft > 0) {
if ((nread = Read (FD, PTR, nleft)) < 0) {
if (errno = = eintr)
nread = 0; /* and call Read () again * *
Else
Return (-1);
else if (nread = 0)
Break /* EOF * *

Nleft-= nread;
PTR + = nread;
}
return (N-nleft); /* Return >= 0 * *
}

ssize_t/* Write "n" bytes to a descriptor. */
writen (int fd, const void *vptr, size_t N)
{
size_t Nleft;
ssize_t Nwritten;
const char *ptr;

ptr = vptr;
Nleft = n;
while (Nleft > 0) {
if ((Nwritten = write (FD, PTR, nleft)) <= 0) {
if (Nwritten < 0 && errno = = eintr)
Nwritten = 0; /* and call Write () again * *
Else
Return (-1); /* ERROR * *
}

Nleft-= Nwritten;
PTR + = Nwritten;
}
return (n);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.