11 # include <sys/random.h>
17 void error(int status, int errnum, const char *format, ...)
21 fprintf(stderr, "%s: ", program_invocation_short_name);
23 vfprintf(stderr, format, ap);
26 fprintf(stderr, ": %s\n", strerror(errnum));
28 fprintf(stderr, "\n");
34 int close_stream(FILE *stream)
36 const int flush_status = fflush(stream);
37 #ifdef HAVE___FPENDING
38 const int some_pending = (__fpending(stream) != 0);
40 const int prev_fail = (ferror(stream) != 0);
41 const int fclose_fail = (fclose(stream) != 0);
44 prev_fail || (fclose_fail && (
45 #ifdef HAVE___FPENDING
49 if (!fclose_fail && !(errno == EPIPE))
56 void close_stdout(void)
58 if (close_stream(stdout) != 0 && !(errno == EPIPE)) {
60 error(0, errno, "write error");
62 error(0, 0, "write error");
65 if (close_stream(stderr) != 0)
69 long strtol_or_err(char const *const str, char const *const errmesg,
70 const long min, const long max)
76 if (str == NULL || *str == '\0')
78 num = strtol(str, &end, 10);
79 if (errno || str == end || (end && *end))
81 if (num < min || max < num)
82 error(EXIT_FAILURE, 0, "%s: '%s': out of range: %lu <= value <= %lu",
83 errmesg, str, min, max);
86 error(EXIT_FAILURE, errno, "%s: '%s'", errmesg, str);
90 static unsigned int iputil_srand_fallback(void)
94 clock_gettime(CLOCK_REALTIME, &ts);
95 return ((getpid() << 16) ^ getuid() ^ ts.tv_sec ^ ts.tv_nsec);
98 void iputils_srand(void)
107 ret = getrandom(&i, sizeof(i), GRND_NONBLOCK);
114 i = iputil_srand_fallback();
117 } while (ret != sizeof(i));
120 i = iputil_srand_fallback();
123 /* Consume up to 31 random numbers */
131 void timespecsub(struct timespec *a, struct timespec *b, struct timespec *res)
133 res->tv_sec = a->tv_sec - b->tv_sec;
134 res->tv_nsec = a->tv_nsec - b->tv_nsec;
136 if (res->tv_nsec < 0) {
138 res->tv_nsec += 1000000000L;