morpheus-base

morpheus base system
git clone git://git.2f30.org/morpheus-base
Log | Files | Refs

renice.c (1838B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <errno.h>
      3 #include <limits.h>
      4 #include <pwd.h>
      5 #include <stdio.h>
      6 #include <stdlib.h>
      7 #include <string.h>
      8 #include <sys/resource.h>
      9 
     10 #include "util.h"
     11 
     12 static int strtop(const char *);
     13 static int renice(int, int, long);
     14 
     15 static void
     16 usage(void)
     17 {
     18 	eprintf("renice -n inc [-g | -p | -u] ID ...\n");
     19 }
     20 
     21 int
     22 main(int argc, char *argv[])
     23 {
     24 	const char *adj = NULL;
     25 	long val;
     26 	int i, which = PRIO_PROCESS, status = 0;
     27 	struct passwd *pw;
     28 	int who;
     29 
     30 	ARGBEGIN {
     31 	case 'n':
     32 		adj = EARGF(usage());
     33 		break;
     34 	case 'g':
     35 		which = PRIO_PGRP;
     36 		break;
     37 	case 'p':
     38 		which = PRIO_PROCESS;
     39 		break;
     40 	case 'u':
     41 		which = PRIO_USER;
     42 		break;
     43 	default:
     44 		usage();
     45 		break;
     46 	} ARGEND;
     47 
     48 	if (argc == 0 || !adj)
     49 		usage();
     50 
     51 	val = estrtol(adj, 10);
     52 	for (i = 0; i < argc; i++) {
     53 		who = -1;
     54 		if (which == PRIO_USER) {
     55 			errno = 0;
     56 			pw = getpwnam(argv[i]);
     57 			if (!pw) {
     58 				if (errno != 0)
     59 					weprintf("getpwnam %s:", argv[i]);
     60 				else
     61 					weprintf("getpwnam %s: no user found\n", argv[i]);
     62 				status = 1;
     63 				continue;
     64 			}
     65 			who = pw->pw_uid;
     66 		}
     67 		if (who < 0)
     68 			who = strtop(argv[i]);
     69 
     70 		if (who < 0 || !renice(which, who, val))
     71 			status = 1;
     72 	}
     73 
     74 	return status;
     75 }
     76 
     77 static int
     78 strtop(const char *s)
     79 {
     80 	char *end;
     81 	long n;
     82 
     83 	errno = 0;
     84 	n = strtol(s, &end, 10);
     85 	if (*end != '\0') {
     86 		weprintf("%s: not an integer\n", s);
     87 		return -1;
     88 	}
     89 	if (errno != 0 || n <= 0 || n > INT_MAX) {
     90 		weprintf("%s: invalid value\n", s);
     91 		return -1;
     92 	}
     93 
     94 	return (int)n;
     95 }
     96 
     97 static int
     98 renice(int which, int who, long adj)
     99 {
    100 	errno = 0;
    101 	adj += getpriority(which, who);
    102 	if (errno != 0) {
    103 		weprintf("getpriority %d:", who);
    104 		return 0;
    105 	}
    106 
    107 	adj = MAX(PRIO_MIN, MIN(adj, PRIO_MAX));
    108 	if (setpriority(which, who, (int)adj) < 0) {
    109 		weprintf("setpriority %d:", who);
    110 		return 0;
    111 	}
    112 
    113 	return 1;
    114 }