]> pd.if.org Git - pdutils/blob - posix/nice/nice.c
rename utils to posix
[pdutils] / posix / nice / nice.c
1 #define _POSIX_C_SOURCE 200809L
2 #define _XOPEN_SOURCE
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <unistd.h>
7 #include <limits.h>
8 #include <errno.h>
9
10 /* Public domain by Nathan Wagner */
11
12 /* reads a long from a string.  returns -1 if completely
13  * read, number of characters read otherwise,
14  * or zero if it can't read a string
15  * clears errno, which may be reset again by strtol()
16  */
17 static int readint(char *s, long *i) {
18         long val;
19         char *end;
20         errno = 0;
21         val = strtol(s, &end, 10);
22
23         /* Check for various possible errors */
24
25         if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
26                         || (errno != 0 && val == 0)) {
27                 perror("strtol");
28                 return 0;
29         }
30
31         if (end == s) {
32                 fprintf(stderr, "No digits were found\n");
33                 return 0;
34         }
35
36         /* If we got here, strtol() successfully parsed a number */
37
38         *i = val;
39
40         if (*end != '\0') {
41                 /* Not necessarily an error... */
42                 /* printf("Further characters after number: %s\n", endptr); */
43                 return end - s;
44         }
45
46         return -1;
47 }
48
49 static void usage(void) {
50         fprintf(stderr, "usage: nice [-n increment] utility [argument...]\n");
51         exit(1);
52 }
53
54 int main(int ac, char *av[]) {
55         int arg;
56         arg = 1;
57         long nval;
58         if (arg < ac && !strcmp(av[arg], "-n")) {
59                 char *s = 0;
60                 if (av[arg][2]) {
61                         s = av[arg]+2;
62                 } else if (++arg < ac) {
63                         s = av[arg];
64                 }
65                 if (s && (readint(s, &nval) == -1)) {
66                         nice((int)nval);
67                         arg++;
68                 } else {
69                         usage();
70                 }
71         }
72
73         if (arg < ac) {
74                 execvp(av[arg], &av[arg]);
75                 switch (errno) {
76                         case ENOENT:
77                                 fprintf(stderr, "nice: ");
78                                 perror(av[arg]);
79                                 return 127;
80                         default:
81                                 fprintf(stderr, "nice: ");
82                                 perror(av[arg]);
83                                 return 126;
84                 }
85         } else {
86                 usage();
87         }
88
89         return 1;
90 }