sbase/renice.c

113 lines
1.8 KiB
C
Raw Normal View History

/* See LICENSE file for copyright and license details. */
2015-02-14 20:02:41 +00:00
#include <sys/resource.h>
2014-11-17 16:32:30 +00:00
#include <errno.h>
#include <pwd.h>
#include <stdlib.h>
#include "util.h"
static int strtop(const char *);
static int renice(int, int, long);
2014-04-22 12:13:51 +00:00
static void
usage(void)
{
eprintf("renice -n inc [-g | -p | -u] ID ...\n");
}
int
2014-04-18 10:51:18 +00:00
main(int argc, char *argv[])
{
const char *adj = NULL;
long val;
2014-10-02 22:46:04 +00:00
int i, which = PRIO_PROCESS, status = 0;
2014-11-17 16:32:30 +00:00
struct passwd *pw;
int who;
ARGBEGIN {
case 'n':
adj = EARGF(usage());
break;
case 'g':
which = PRIO_PGRP;
break;
case 'p':
which = PRIO_PROCESS;
break;
case 'u':
which = PRIO_USER;
break;
default:
usage();
break;
} ARGEND;
if (argc == 0 || !adj)
usage();
val = estrtonum(adj, PRIO_MIN, PRIO_MAX);
for (i = 0; i < argc; i++) {
2014-11-17 16:32:30 +00:00
who = -1;
if (which == PRIO_USER) {
errno = 0;
2014-11-17 16:32:30 +00:00
pw = getpwnam(argv[i]);
if (!pw) {
if (errno != 0)
weprintf("getpwnam %s:", argv[i]);
else
weprintf("getpwnam %s: no user found\n", argv[i]);
2014-10-02 22:46:04 +00:00
status = 1;
continue;
}
2014-11-17 16:32:30 +00:00
who = pw->pw_uid;
}
if (who < 0)
who = strtop(argv[i]);
if (who < 0 || !renice(which, who, val))
2014-10-02 22:46:04 +00:00
status = 1;
}
return status;
}
static int
strtop(const char *s)
{
char *end;
long n;
errno = 0;
n = strtol(s, &end, 10);
if (*end != '\0') {
weprintf("%s: not an integer\n", s);
return -1;
}
if (errno != 0 || n <= 0 || n > INT_MAX) {
weprintf("%s: invalid value\n", s);
return -1;
}
return (int)n;
}
static int
renice(int which, int who, long adj)
{
errno = 0;
adj += getpriority(which, who);
if (errno != 0) {
weprintf("getpriority %d:", who);
return 0;
}
adj = MAX(PRIO_MIN, MIN(adj, PRIO_MAX));
2014-11-19 19:59:37 +00:00
if (setpriority(which, who, (int)adj) < 0) {
weprintf("setpriority %d:", who);
return 0;
}
return 1;
}