From: Nathan Wagner Date: Sat, 25 Apr 2015 23:25:47 +0000 (+0000) Subject: implemented nice X-Git-Url: https://pd.if.org/git/?p=pdutils;a=commitdiff_plain;h=252f8cd3b8783b1b74f3438ae0d771ec0a192a87 implemented nice --- diff --git a/utils/nice/nice.c b/utils/nice/nice.c new file mode 100644 index 0000000..7aab5b2 --- /dev/null +++ b/utils/nice/nice.c @@ -0,0 +1,90 @@ +#define _POSIX_C_SOURCE 200809L +#define _XOPEN_SOURCE +#include +#include +#include +#include +#include +#include + +/* Public domain by Nathan Wagner */ + +/* reads a long from a string. returns -1 if completely + * read, number of characters read otherwise, + * or zero if it can't read a string + * clears errno, which may be reset again by strtol() + */ +static int readint(char *s, long *i) { + long val; + char *end; + errno = 0; + val = strtol(s, &end, 10); + + /* Check for various possible errors */ + + if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) + || (errno != 0 && val == 0)) { + perror("strtol"); + return 0; + } + + if (end == s) { + fprintf(stderr, "No digits were found\n"); + return 0; + } + + /* If we got here, strtol() successfully parsed a number */ + + *i = val; + + if (*end != '\0') { + /* Not necessarily an error... */ + /* printf("Further characters after number: %s\n", endptr); */ + return end - s; + } + + return -1; +} + +static void usage(void) { + fprintf(stderr, "usage: nice [-n increment] utility [argument...]\n"); + exit(1); +} + +int main(int ac, char *av[]) { + int arg; + arg = 1; + long nval; + if (arg < ac && !strcmp(av[arg], "-n")) { + char *s = 0; + if (av[arg][2]) { + s = av[arg]+2; + } else if (++arg < ac) { + s = av[arg]; + } + if (s && (readint(s, &nval) == -1)) { + nice((int)nval); + arg++; + } else { + usage(); + } + } + + if (arg < ac) { + execvp(av[arg], &av[arg]); + switch (errno) { + case ENOENT: + fprintf(stderr, "nice: "); + perror(av[arg]); + return 127; + default: + fprintf(stderr, "nice: "); + perror(av[arg]); + return 126; + } + } else { + usage(); + } + + return 1; +}