logo

utils-std

Collection of commonly available Unix tools
commit: e4244694098da65e31b7c342c2c217cb1123110b
parent 36741fde59e60937b7016e46f1223f4c8d917aca
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Fri, 23 Aug 2024 04:51:28 +0200

cmd/yes: switch to C

Diffstat:

MMakefile2+-
Dcmd/yes13-------------
Acmd/yes.c45+++++++++++++++++++++++++++++++++++++++++++++
Mtest-cmd/yes.t6++----
4 files changed, 48 insertions(+), 18 deletions(-)

diff --git a/Makefile b/Makefile @@ -4,7 +4,7 @@ include config.mk # Commands implemented as scripts -SCRIPTS=cmd/yes +SCRIPTS= # Commands linking to another executable SYMLINKS=cmd/'[' cmd/chgrp cmd/readlink diff --git a/cmd/yes b/cmd/yes @@ -1,13 +0,0 @@ -#!/bin/sh -# utils-std: Collection of commonly available Unix tools -# SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me> -# SPDX-License-Identifier: MPL-2.0 - -die() { - echo "yes: $@" >&2 - exit 1 -} - -while :; do - echo "${@:-y}" || die "Write error" -done diff --git a/cmd/yes.c b/cmd/yes.c @@ -0,0 +1,45 @@ +// utils-std: Collection of commonly available Unix tools +// SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me> +// SPDX-License-Identifier: MPL-2.0 + +#define _POSIX_C_SOURCE 200809L +#include <stdbool.h> +#include <stdio.h> // fwrite, perror, ferror +#include <string.h> // strlen + +int +main(int argc, char *argv[]) +{ + size_t arg_len = 0; + + argv++; + argc--; + + for(int i = 0; i < argc; i++) + { + size_t len = strlen(argv[i]); + + if(len > 0) + { + argv[i][len] = (i + 1) == argc ? '\n' : ' '; + arg_len += len + 1; // str + space|newline + } + } + + if(arg_len == 0) + { + *argv = "y\n"; + arg_len = 2; + } + + while(fwrite(*argv, arg_len, 1, stdout) == 1) + ; + + if(ferror(stdout)) + { + perror("yes: Write Error"); + return 1; + } + + return 0; +} diff --git a/test-cmd/yes.t b/test-cmd/yes.t @@ -21,8 +21,6 @@ foo bar -Error messages from echo needs to be filtered out as it's often a shell builtin - $ set -o pipefail - $ yes 2>&1 >/dev/full | grep -v echo: - yes: Write error + $ yes 2>&1 >/dev/full + yes: Write Error: No space left on device [1]