1 /* chrt.c - Get/set real-time (scheduling) attributes
2 *
3 * Copyright 2016 The Android Open Source Project
4 *
5 * Note: -ibrfo flags sorted to match SCHED positions for highest_bit()
6
7 USE_CHRT(NEWTOY(chrt, "^mp#<0iRbrfo[!ibrfo]", TOYFLAG_USR|TOYFLAG_SBIN))
8
9 config CHRT
10 bool "chrt"
11 default y
12 help
13 usage: chrt [-Rmofrbi] {-p PID [PRIORITY] | [PRIORITY COMMAND...]}
14
15 Get/set a process' real-time scheduling policy and priority.
16
17 -p Set/query given pid (instead of running COMMAND)
18 -R Set SCHED_RESET_ON_FORK
19 -m Show min/max priorities available
20
21 Set policy (default -r):
22
23 -o SCHED_OTHER -f SCHED_FIFO -r SCHED_RR
24 -b SCHED_BATCH -i SCHED_IDLE
25 */
26
27 #define FOR_chrt
28 #include "toys.h"
29
30 GLOBALS(
31 long pid;
32 )
33
34 char *polnames[] = {
35 "SCHED_OTHER", "SCHED_FIFO", "SCHED_RR", "SCHED_BATCH", 0, "SCHED_IDLE",
36 "SCHED_DEADLINE"
37 };
38
chrt_main(void)39 void chrt_main(void)
40 {
41 int pol, pri;
42
43 // Show min/maxes?
44 if (toys.optflags&FLAG_m) {
45 for (pol = 0; pol<ARRAY_LEN(polnames); pol++) if (polnames[pol])
46 printf("%s min/max priority\t: %d/%d\n", polnames[pol],
47 sched_get_priority_min(pol), sched_get_priority_max(pol));
48
49 return;
50 }
51
52 // Query when -p without priority.
53 if (toys.optflags==FLAG_p && !*toys.optargs) {
54 char *s = "???", *R = "";
55
56 if (-1==(pol = sched_getscheduler(TT.pid))) perror_exit("pid %ld", TT.pid);
57 if (pol & SCHED_RESET_ON_FORK) R = "|SCHED_RESET_ON_FORK";
58 if ((pol &= ~SCHED_RESET_ON_FORK)<ARRAY_LEN(polnames)) s = polnames[pol];
59 printf("pid %ld's current scheduling policy: %s%s\n", TT.pid, s, R);
60
61 if (sched_getparam(TT.pid, (void *)&pri)) perror_exit("sched_getparam");
62 printf("pid %ld's current scheduling priority: %d\n", TT.pid, pri);
63
64 return;
65 }
66
67 if (!*toys.optargs) help_exit("no PRIORITY");
68 if (!toys.optargs[1] == !(toys.optflags&FLAG_p))
69 help_exit("need 1 of -p or COMMAND");
70
71 // Set policy and priority
72 if (-1==(pol = highest_bit(toys.optflags&0x2f))) pol = SCHED_RR;
73 pri = atolx_range(*toys.optargs, sched_get_priority_min(pol),
74 sched_get_priority_max(pol));
75 if (toys.optflags&FLAG_R) pol |= SCHED_RESET_ON_FORK;
76
77 if (sched_setscheduler(TT.pid, pol, (void *)&pri))
78 perror_exit("sched_setscheduler");
79
80 if (*(toys.optargs+1)) xexec(toys.optargs+1);
81 }
82