* Note that we use the GNU variant of strerror_r() here. */
#define STRERROR(errnum) strerror_r(abs(errnum), (char[ERRNO_BUF_LEN]){}, ERRNO_BUF_LEN)
+/* A helper to print an error message or message for functions that return 0 on EOF.
+ * Note that we can't use ({ … }) to define a temporary variable, so errnum is
+ * evaluated twice. */
+#define STRERROR_OR_EOF(errnum) ((errnum) != 0 ? STRERROR(errnum) : "Unexpected EOF")
+
static inline void _reset_errno_(int *saved_errno) {
if (*saved_errno < 0) /* Invalidated by UNPROTECT_ERRNO? */
return;
errno = 0;
k = fread(buf, 1, n, m->tmp);
if (k != n) {
- log_error("Failed to read from file: %s", errno != 0 ? strerror_safe(errno) : "Premature EOF");
+ log_error("Failed to read from file: %s", STRERROR_OR_EOF(errno));
return MHD_CONTENT_READER_END_WITH_ERROR;
}
errno = 0;
k = fread(buf, 1, n, m->tmp);
if (k != n) {
- log_error("Failed to read from file: %s", errno != 0 ? strerror_safe(errno) : "Premature EOF");
+ log_error("Failed to read from file: %s", STRERROR_OR_EOF(errno));
return MHD_CONTENT_READER_END_WITH_ERROR;
}
errno = 0;
if (read(pp[0], &x, 1) <= 0) {
- log_error("Failed to read from pipe: %s", errno != 0 ? strerror_safe(errno) : "early read");
+ log_error("Failed to read from pipe: %s", STRERROR_OR_EOF(errno));
goto finish;
}
if (lseek(s->manager->console_active_fd, SEEK_SET, 0) < 0)
return log_error_errno(errno, "lseek on console_active_fd failed: %m");
+ errno = 0;
k = read(s->manager->console_active_fd, t, sizeof(t)-1);
- if (k <= 0) {
- log_error("Failed to read current console: %s", k < 0 ? strerror_safe(errno) : "EOF");
- return k < 0 ? -errno : -EIO;
- }
+ if (k <= 0)
+ return log_error_errno(errno ?: EIO,
+ "Failed to read current console: %s", STRERROR_OR_EOF(errno));
t[k] = 0;
truncate_nl(t);
assert_se(strstr(c, buf));
}
+TEST(STRERROR_OR_ELSE) {
+ log_info("STRERROR_OR_ELSE(0, \"EOF\") → %s", STRERROR_OR_EOF(0));
+ log_info("STRERROR_OR_ELSE(EPERM, \"EOF\") → %s", STRERROR_OR_EOF(EPERM));
+ log_info("STRERROR_OR_ELSE(-EPERM, \"EOF\") → %s", STRERROR_OR_EOF(-EPERM));
+}
+
DEFINE_TEST_MAIN(LOG_INFO);