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 /* 00030 * Given the API we have to assume (unsigned) size_t 'count' fits into 00031 * a (signed) ssize_t because we can't return a larger value. 00032 * https://stackoverflow.com/questions/29722999/will-write2-always-write-less-than-or-equal-to-ssize-max 00033 */ 00034 ssize_t out, tot = 0; 00035 00036 if (!buf || count == 0) 00037 return 0; 00038 00039 while ((size_t) tot < count) { 00040 out = write(fd, (const char *) buf + tot, count - tot); 00041 if (out > 0) 00042 tot += out; 00043 else if(errno == EAGAIN || errno == EINTR) 00044 continue; 00045 else { 00046 if (written) 00047 *written = tot; 00048 return out; 00049 } 00050 } 00051 if (written) 00052 *written = tot; 00053 return tot; 00054 } 00055 00056 /** @} */ 00057 #endif /* LIBNAGIOS_NWRITE_H_INCLUDED */