Write function
# Include <unistd. h>
Ssize_t write (INT Fildes, const void * Buf, size_t nbyte)
The Write function writes the nbyte bytes in the Buf to the open file referenced by the file descriptor FD. If the file is successful, the number of written bytes is returned. If the file fails, the value-1 is returned. And set the errno variable. In the network program, there are two possibilities when we write to the socket file descriptor.
1) the return value of write is greater than 0, indicating that some or all data is written.
2) If the returned value is less than 0, an error occurs. We need to handle the error based on the error type.
If the error is eintr, an interruption error occurs during write.
If it is epipe, the network connection is faulty (the other party has closed the connection ).
To handle the above situations, we compile a write function to handle these situations.
Ssize_t writen (int fd, const void * Buf, size_t num) {ssize_t res; size_t N; const char * PTR; n = num; PTR = Buf; while (n> 0) {/* start to write */If (RES = write (FD, PTR, n) <= 0) {If (errno = eintr) RES = 0; else return (-1);} PTR + = res;/* continue to write */n-= res;} return (Num );}
Read Function
The ssize_t read (INT Fildes, void * Buf, size_t nbyte) read function is used to read the nbyte bytes from the open file referenced by FD to the buffer zone pointed to by the Buf, the number of actually read bytes is returned. If the returned value is 0, it indicates that the object has been read. If the value is smaller than 0, an error occurs. If the error is eintr, the read operation is interrupted. if the error is econnrest, the network connection is faulty. It is possible that the number of bytes read by read is less than the required nbyte. There are many reasons: 1. Read from the rule file. reading from the terminal usually reads one row at a time, read from a TCP socket any number of bytes that can be returned based on how the packet is accepted.
Like above, we also write our own READ function.
ssize_t readn (int fd, void *buf, size_t num){ssize_t res;size_t n;char *ptr;n = num;ptr = buf;while (n > 0) { if ((res = read (fd, ptr, n)) == -1) { if (errno == EINTR) res = 0; else return (-1); } else if (res == 0) break; ptr += res; n -= res;}return (num - n);}