xref: /original-bsd/usr.bin/renice/renice.c (revision 5e36add1)
1 /*
2  * Copyright (c) 1983 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 char copyright[] =
10 "@(#) Copyright (c) 1989 The Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)renice.c	5.3 (Berkeley) 06/01/90";
16 #endif /* not lint */
17 
18 #include <sys/time.h>
19 #include <sys/resource.h>
20 #include <stdio.h>
21 #include <pwd.h>
22 
23 /*
24  * Change the priority (nice) of processes
25  * or groups of processes which are already
26  * running.
27  */
28 main(argc, argv)
29 	char **argv;
30 {
31 	int which = PRIO_PROCESS;
32 	int who = 0, prio, errs = 0;
33 
34 	argc--, argv++;
35 	if (argc < 2) {
36 		fprintf(stderr, "usage: renice priority [ [ -p ] pids ] ");
37 		fprintf(stderr, "[ [ -g ] pgrps ] [ [ -u ] users ]\n");
38 		exit(1);
39 	}
40 	prio = atoi(*argv);
41 	argc--, argv++;
42 	if (prio > PRIO_MAX)
43 		prio = PRIO_MAX;
44 	if (prio < PRIO_MIN)
45 		prio = PRIO_MIN;
46 	for (; argc > 0; argc--, argv++) {
47 		if (strcmp(*argv, "-g") == 0) {
48 			which = PRIO_PGRP;
49 			continue;
50 		}
51 		if (strcmp(*argv, "-u") == 0) {
52 			which = PRIO_USER;
53 			continue;
54 		}
55 		if (strcmp(*argv, "-p") == 0) {
56 			which = PRIO_PROCESS;
57 			continue;
58 		}
59 		if (which == PRIO_USER) {
60 			register struct passwd *pwd = getpwnam(*argv);
61 
62 			if (pwd == NULL) {
63 				fprintf(stderr, "renice: %s: unknown user\n",
64 					*argv);
65 				continue;
66 			}
67 			who = pwd->pw_uid;
68 		} else {
69 			who = atoi(*argv);
70 			if (who < 0) {
71 				fprintf(stderr, "renice: %s: bad value\n",
72 					*argv);
73 				continue;
74 			}
75 		}
76 		errs += donice(which, who, prio);
77 	}
78 	exit(errs != 0);
79 }
80 
81 donice(which, who, prio)
82 	int which, who, prio;
83 {
84 	int oldprio;
85 	extern int errno;
86 
87 	errno = 0, oldprio = getpriority(which, who);
88 	if (oldprio == -1 && errno) {
89 		fprintf(stderr, "renice: %d: ", who);
90 		perror("getpriority");
91 		return (1);
92 	}
93 	if (setpriority(which, who, prio) < 0) {
94 		fprintf(stderr, "renice: %d: ", who);
95 		perror("setpriority");
96 		return (1);
97 	}
98 	printf("%d: old priority %d, new priority %d\n", who, oldprio, prio);
99 	return (0);
100 }
101