nice.c (1928B)
- // 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
- #define _XOPEN_SOURCE 700 // nice() is in XSI
- #include <assert.h>
- #include <errno.h>
- #include <stdio.h> // fprintf
- #include <stdlib.h> // abort
- #include <string.h> // strerror
- #include <unistd.h> // getopt, nice
- const char *argv0 = "nice";
- static void
- usage(void)
- {
- fprintf(stderr, "Usage: nice [-n increment] command [argument ...]\n");
- }
- int
- main(int argc, char *argv[])
- {
- long incr = 0;
- int c = -1;
- while((c = getopt(argc, argv, ":n:")) != -1)
- {
- char *endptr = NULL;
- switch(c)
- {
- case 'n':
- incr = strtol(optarg, &endptr, 10);
- if(endptr && *endptr != 0) errno = EINVAL;
- if(errno != 0)
- {
- fprintf(stderr,
- "%s: error: Failed parsing '%s' as a number: %s\n",
- argv0,
- optarg,
- strerror(errno));
- usage();
- return 125;
- }
- break;
- case ':':
- fprintf(stderr, "%s: error: Missing operand for option: '-%c'\n", argv0, optopt);
- usage();
- return 125;
- case '?':
- fprintf(stderr, "%s: error: Unrecognised option: '-%c'\n", argv0, optopt);
- usage();
- return 125;
- default:
- abort();
- }
- }
- argc -= optind;
- argv += optind;
- if(argc == 0) return 0;
- errno = 0;
- if(nice((int)incr) == -1)
- {
- switch(errno)
- {
- case 0:
- break;
- case EPERM:
- fprintf(
- stderr, "%s: warning: Failed setting nice to %ld: %s\n", argv0, incr, strerror(errno));
- errno = 0;
- break;
- default:
- fprintf(stderr, "%s: error: Failed setting nice to %ld: %s\n", argv0, incr, strerror(errno));
- return 125;
- }
- }
- assert(argv[0]);
- if(execvp(argv[0], argv) < 0)
- {
- fprintf(stderr, "%s: error: Failed executing '%s': %s\n", argv0, argv[0], strerror(errno));
- return (errno == ENOENT) ? 127 : 126;
- }
- abort();
- }