Linux Data write operation improvements

Source: Internet
Author: User

The write function of the data in the IO operation of Linux int nwrite = write (int fd,void* buf, int len) represents a data packet written to Len byte length to the FD file descriptor, but this does not guarantee that Len data is actually written to the kernel buffer. For example, when the kernel socket buffer is insufficient, less than Len bytes, it will write only a portion of it, returning nwrite represents the actual number of bytes written: Because this read-write method guarantees that the data is all written to the buffer, so the actual return value only-1 for the write error, size represents a full write buffer.

In order to ensure the integrity of the data write, it is necessary to use cyclic writing, the following is the reference code:

1#include <unistd.h>2#include <stdio.h>3#include <errno.h>4#include <iostream>5 using namespacestd;6ssize_t writen (intFdvoid*buf, size_t size)7 {8     Char*ptr = (Char*) buf;9     intNleft = (int) size;Ten     intNwritten; One      while(Nleft >0) A     { -Nwritten =write (FD, PTR, nleft); -         if(Nwritten <=0) the         { -             if(Nwritten <0&& errno&eintr)//the error continues to read or write -             { -Nwritten =0;//Write again +             } -             Else  +                 return-1;//Error A         } atNleft-=Nwritten; -PTR + =Nwritten; -     } -     returnsize; -}

Linux Data write operation improvements

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.