logo

utils-std

Collection of commonly available Unix tools
commit: 27d1d702d23ca5cbfe38b8215da801789f94899c
parent 33ce03eb7634e16c414b12f00c5ae78c794c8a56
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Fri, 12 Apr 2024 20:05:33 +0200

cmd/echo: More detailed error messages

Diffstat:

Mcmd/echo.c24+++++++++++++++---------
Mtest-cmd/echo2+-
2 files changed, 16 insertions(+), 10 deletions(-)

diff --git a/cmd/echo.c b/cmd/echo.c @@ -3,11 +3,12 @@ // SPDX-License-Identifier: MPL-2.0 #define _POSIX_C_SOURCE 200809L -#include <stdbool.h> /* bool */ -#include <stdio.h> /* perror */ -#include <stdlib.h> /* malloc */ -#include <string.h> /* strlen */ -#include <unistd.h> /* write */ +#include <errno.h> +#include <stdbool.h> +#include <stdio.h> // fprintf +#include <stdlib.h> // malloc +#include <string.h> // strerror, strlen +#include <unistd.h> // write int main(int argc, char *argv[]) @@ -35,7 +36,7 @@ main(int argc, char *argv[]) if(write(1, "\n", 1) < 1) { - perror("echo: write(1, \"\n\", 1)"); + fprintf(stderr, "echo: Write error: %s\n", strerror(errno)); return 1; } @@ -47,7 +48,7 @@ main(int argc, char *argv[]) buffer = malloc(arg_len); if(buffer == NULL) { - perror("echo: malloc(arg_len)"); + fprintf(stderr, "echo: Memory allocation error, malloc(%zu): %s\n", arg_len, strerror(errno)); return 1; } @@ -65,9 +66,14 @@ main(int argc, char *argv[]) } if(!opt_n) *buffer_p++ = '\n'; - if(write(1, buffer, arg_len) < (ssize_t)arg_len) + ssize_t nwrite = write(1, buffer, arg_len); + if(nwrite < (ssize_t)arg_len) { - perror("echo: write(1, buffer, arg_len)"); + fprintf(stderr, + "echo: Write error, write(1, buffer, %zu) = %zd: %s\n", + arg_len, + nwrite, + strerror(errno)); err++; } diff --git a/test-cmd/echo b/test-cmd/echo @@ -19,7 +19,7 @@ doubledash_body() { atf_test_case devfull devfull_body() { - atf_check -s exit:1 -e 'inline:echo: write(1, buffer, arg_len): No space left on device\n' sh -c '../cmd/echo hello world >/dev/full' + atf_check -s exit:1 -e 'inline:echo: Write error, write(1, buffer, 12) = -1: No space left on device\n' sh -c '../cmd/echo hello world >/dev/full' } atf_test_case opt_n