]> pd.if.org Git - pdutils/commitdiff
implemented nice
authorNathan Wagner <nw@hydaspes.if.org>
Sat, 25 Apr 2015 23:25:47 +0000 (23:25 +0000)
committerNathan Wagner <nw@hydaspes.if.org>
Thu, 30 Apr 2015 02:28:43 +0000 (02:28 +0000)
utils/nice/nice.c [new file with mode: 0644]

diff --git a/utils/nice/nice.c b/utils/nice/nice.c
new file mode 100644 (file)
index 0000000..7aab5b2
--- /dev/null
@@ -0,0 +1,90 @@
+#define _POSIX_C_SOURCE 200809L
+#define _XOPEN_SOURCE
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <limits.h>
+#include <errno.h>
+
+/* 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;
+}