00001 #ifndef LIBNAGIOS_NWRITE_H_INCLUDED 00002 #define LIBNAGIOS_NWRITE_H_INCLUDED 00003 00004 /** 00005 * @file nwrite.h 00006 * @brief Functions that properly handle incomplete write()'s 00007 * 00008 * Some functions simply use write() to send data through a socket. 00009 * These calls are sometimes interrupted, especially in the case of 00010 * an overly large buffer. Even though the write() _could_ finish, 00011 * the incomplete write is treated as an error. The functions here 00012 * properly handle those cases. 00013 * 00014 * @{ 00015 */ 00016 00017 /** 00018 * Send data through a socket 00019 * This function will send data through a socket and return 00020 * the number of bytes written. 00021 * @param sock The socket to write to 00022 * @param data The data to write 00023 * @param lth The length of the data 00024 * @param sent The number of bytes written (can be NULL) 00025 * @return The number of bytes written or -1 if error 00026 */ 00027 static inline ssize_t nwrite(int fd, const void *buf, size_t count, ssize_t *written) 00028 { 00029 ssize_t out, tot = 0; 00030 00031 if (!buf || count == 0) 00032 return 0; 00033 00034 while (tot < count) { 00035 out = write(fd, buf + tot, count - tot); 00036 if (out > 0) 00037 tot += out; 00038 else if(errno == EAGAIN || errno == EINTR) 00039 continue; 00040 else { 00041 if (written) 00042 *written = tot; 00043 return out; 00044 } 00045 } 00046 if (written) 00047 *written = tot; 00048 return tot; 00049 } 00050 00051 /** @} */ 00052 #endif /* LIBNAGIOS_NWRITE_H_INCLUDED */