1. Writing function Write
Function Prototypes:
size_t write (int fd,constvoid *buf,size_t nbytes);
The Write function writes the nbytes byte content in buf to the file descriptor FD, returns the number of bytes written on success, and returns 1 on failure. In a network program, there are two cases of writing to the socket file descriptor:
1) The return value of write is greater than 0, indicating that some or all of the data is written.
2) The return value is less than 0, and an error occurs, which is handled according to the error type. If the error is eintr, there is an interrupt error when writing, or if the epipe indicates a problem with the network connection (the other side closes the connection).
You can customize the Write function to handle the above situation:
intMy_write (intFdvoid*buffer,intlength) { intBytes_left; intwritten_bytes; Char*ptr; PTR=buffer; Bytes_left=length; while(bytes_left>0) { /*Start Writing*/written_bytes=write (FD, PTR, bytes_left); if(Written_bytes <=0)/*something went wrong.*/ { if(errno = = eintr)/*Interrupt Error We continue to write*/written_bytes=0; Else /*no other mistakes, no way, but retreat.*/ return(-1); } bytes_left-=written_bytes; PTR+ = Written_bytes;/*keep writing from the rest of the place.*/ } return(0);}
2. Reading function read
Function Prototypes:
size_t Read (int fd,void *buf,size_t nbytes);
The read function is responsible for reading the content from FD. When read is successful, read returns the number of bytes actually read. If the returned value is 0, the end of the file has been read, and less than 0 indicates an error: If the error is eintr, the read is caused by an interrupt, if econnrest indicates a problem with the network connection.
You can customize the read function to handle the above situation:
intMy_read (intFdvoid*buffer,intlength) { intBytes_left; intBytes_read; Char*ptr; Bytes_left=length; while(bytes_left>0) {Bytes_read=Read (FD, PTR, bytes_read); if(bytes_read<0) { if(errno = =eintr) Bytes_read=0; Else return(-1); } Else if(Bytes_read = =0) Break; Bytes_left-=Bytes_read; PTR+=Bytes_read; } return(Length-bytes_left);}
Iv. Network Programming-read and write functions