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