]> git.saurik.com Git - apple/system_cmds.git/blob - mean.tproj/mean.c
system_cmds-735.tar.gz
[apple/system_cmds.git] / mean.tproj / mean.c
1 /*
2 * mean.c
3 * mean - lower process priorities with more force than nice
4 *
5 * Created by Lucia Ballard on 9/16/09.
6 * Copyright 2009-2016 Apple Inc. All rights reserved.
7 *
8 */
9
10 #include <mach/mach.h>
11 #include <mach/task.h>
12 #include <mach/thread_act.h>
13 #include <mach/thread_policy.h>
14
15 #include <errno.h>
16 #include <getopt.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19
20 void usage(void);
21
22 void
23 usage(void)
24 {
25 fprintf(stderr, "Usage: mean -[r|s|u] <pid>\n");
26 fprintf(stderr, "\tLower <pid>'s priority.\n");
27 fprintf(stderr, "\t-u: return <pid> to normal priority\n");
28 fprintf(stderr, "\t-r: resume <pid>\n");
29 fprintf(stderr, "\t-s: suspend <pid>\n");
30 exit(0);
31 }
32
33 int
34 main(int argc, char **argv)
35 {
36 int pid, err, i, ch;
37 unsigned int count;
38 mach_port_t task;
39 thread_act_array_t threads;
40 thread_precedence_policy_data_t policy;
41
42 boolean_t do_high = 0, do_resume = 0, do_suspend = 0;
43 boolean_t do_low = 1;
44
45 if (argc < 2)
46 usage();
47
48 while ((ch = getopt(argc, argv, "rsu")) != -1)
49 switch (ch) {
50 case 'u':
51 do_high = 1;
52 do_low = 0;
53 continue;
54 case 'r':
55 do_resume = 1;
56 do_low = 0;
57 continue;
58 case 's':
59 do_suspend = 1;
60 do_low = 0;
61 continue;
62 default:
63 usage();
64 }
65
66 argc -= optind; argv += optind;
67
68 if (argc == 0)
69 usage();
70
71 pid = atoi(*argv);
72 if (!pid)
73 usage();
74
75 err = task_for_pid(mach_task_self(), pid, &task);
76 if (err) {
77 fprintf(stderr, "Failed to get task port (%d)\n", err);
78 exit(0);
79 }
80
81 if (do_low || do_high) {
82
83 err = task_threads(task, &threads, &count);
84 if (err) {
85 fprintf(stderr, "Failed to get thread list (%d)\n", err);
86 exit(0);
87 }
88
89 if (do_low)
90 policy.importance = -100;
91 else
92 policy.importance = 0;
93
94 for (i = 0; i < count; i++) {
95 err = thread_policy_set(threads[i],
96 THREAD_PRECEDENCE_POLICY,
97 (thread_policy_t) &policy,
98 THREAD_PRECEDENCE_POLICY_COUNT);
99 if (err) {
100 fprintf(stderr, "Failed to set thread priority (%d)\n", err);
101 exit(0);
102 }
103 }
104
105 printf("Process %d's threads set to %s priority.\n", pid,
106 (do_low ? "lowest" : "highest"));
107 }
108
109 if (do_suspend) {
110 err = task_suspend(task);
111 if (err) {
112 fprintf(stderr, "Failed to suspend task (%d)\n", err);
113 } else {
114 printf("Process %d suspended.\n", pid);
115 }
116 }
117
118 if (do_resume) {
119 err = task_resume(task);
120 if (err) {
121 fprintf(stderr, "Failed to resume task (%d)\n", err);
122 } else {
123 printf("Process %d resumed.\n", pid);
124 }
125 }
126
127 return 0;
128 }