Nagios  4.3.4
Dev docs for Nagios core and neb-module hackers
nwrite.h
Go to the documentation of this file.
1 #ifndef LIBNAGIOS_NWRITE_H_INCLUDED
2 #define LIBNAGIOS_NWRITE_H_INCLUDED
3 
4 /**
5  * @file nwrite.h
6  * @brief Functions that properly handle incomplete write()'s
7  *
8  * Some functions simply use write() to send data through a socket.
9  * These calls are sometimes interrupted, especially in the case of
10  * an overly large buffer. Even though the write() _could_ finish,
11  * the incomplete write is treated as an error. The functions here
12  * properly handle those cases.
13  *
14  * @{
15  */
16 
17 /**
18  * Send data through a socket
19  * This function will send data through a socket and return
20  * the number of bytes written.
21  * @param sock The socket to write to
22  * @param data The data to write
23  * @param lth The length of the data
24  * @param sent The number of bytes written (can be NULL)
25  * @return The number of bytes written or -1 if error
26  */
27 static inline ssize_t nwrite(int fd, const void *buf, size_t count, ssize_t *written)
28 {
29  ssize_t out, tot = 0;
30 
31  if (!buf || count == 0)
32  return 0;
33 
34  while (tot < count) {
35  out = write(fd, buf + tot, count - tot);
36  if (out > 0)
37  tot += out;
38  else if(errno == EAGAIN || errno == EINTR)
39  continue;
40  else {
41  if (written)
42  *written = tot;
43  return out;
44  }
45  }
46  if (written)
47  *written = tot;
48  return tot;
49 }
50 
51 /** @} */
52 #endif /* LIBNAGIOS_NWRITE_H_INCLUDED */