Audit nice(1)

1) val is sufficient as "int" (read the standard)
2) BUGFIX: If getpriority fails, it returns -1 and sets errno.
   Previously, it would correctly catch the errno but not take
   care of the fact that by then val has been decremented by 1.
   Only change val if the getpriority-call has been successful.
3) Add LIMIT()-macro from st to increase readability.
4) setpriority returns < 0 on failure
5) Remove bikeshedding-comment. Read the standard if you wonder.
6) return-value trick from env(1)
This commit is contained in:
FRIGN 2015-03-02 16:53:13 +01:00
parent 46f743705b
commit c01641c897
4 changed files with 15 additions and 12 deletions

2
README
View File

@ -47,7 +47,7 @@ The following tools are implemented ('*' == finished, '#' == UTF-8 support,
=* mkfifo yes none =* mkfifo yes none
=* mktemp non-posix none =* mktemp non-posix none
=* mv yes none (-i) =* mv yes none (-i)
=* nice yes none =*| nice yes none
= nl no -d, -f, -h, -l, -p = nl no -d, -f, -h, -l, -p
=* nohup yes none =* nohup yes none
#* paste yes none #* paste yes none

4
nice.1
View File

@ -1,4 +1,4 @@
.Dd January 28, 2015 .Dd March 1, 2015
.Dt NICE 1 .Dt NICE 1
.Os sbase .Os sbase
.Sh NAME .Sh NAME
@ -25,7 +25,7 @@ ranging from
.Sy -20 .Sy -20
(highest priority) (highest priority)
to to
.Sy +19 .Sy +20
(lowest priority). (lowest priority).
Default is 10. Default is 10.
.El .El

19
nice.c
View File

@ -16,8 +16,7 @@ usage(void)
int int
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
long val = 10; int val = 10, r, savederrno;
int savederrno;
ARGBEGIN { ARGBEGIN {
case 'n': case 'n':
@ -28,20 +27,22 @@ main(int argc, char *argv[])
break; break;
} ARGEND; } ARGEND;
if (argc == 0) if (!argc)
usage(); usage();
errno = 0; errno = 0;
val += getpriority(PRIO_PROCESS, 0); r = getpriority(PRIO_PROCESS, 0);
if (errno != 0) if (errno)
weprintf("getpriority:"); weprintf("getpriority:");
val = MAX(PRIO_MIN, MIN(val, PRIO_MAX)); else
if (setpriority(PRIO_PROCESS, 0, val) != 0) val += r;
LIMIT(val, PRIO_MIN, PRIO_MAX);
if (setpriority(PRIO_PROCESS, 0, val) < 0)
weprintf("setpriority:"); weprintf("setpriority:");
/* POSIX specifies the nice failure still invokes the command */
execvp(argv[0], argv); execvp(argv[0], argv);
savederrno = errno; savederrno = errno;
weprintf("execvp %s:", argv[0]); weprintf("execvp %s:", argv[0]);
return (savederrno == ENOENT)? 127 : 126;
return 126 + (savederrno == ENOENT);
} }

2
util.h
View File

@ -13,6 +13,8 @@
#define MIN(x,y) ((x) < (y) ? (x) : (y)) #define MIN(x,y) ((x) < (y) ? (x) : (y))
#undef MAX #undef MAX
#define MAX(x,y) ((x) > (y) ? (x) : (y)) #define MAX(x,y) ((x) > (y) ? (x) : (y))
#undef LIMIT
#define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
#define LEN(x) (sizeof (x) / sizeof *(x)) #define LEN(x) (sizeof (x) / sizeof *(x))