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