]> git.saurik.com Git - apple/system_cmds.git/blob - system_cmds-597.1.1/mean.tproj/mean.c
4ea92553b0d6f03dac7991e1cde0082264b33811
[apple/system_cmds.git] / system_cmds-597.1.1 / 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 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
23 void
24 usage(void)
25 {
26 fprintf(stderr, "Usage: mean -[r|s|u] <pid>\n");
27 fprintf(stderr, "\tLower <pid>'s priority.\n");
28 fprintf(stderr, "\t-u: return <pid> to normal priority\n");
29 fprintf(stderr, "\t-r: resume <pid>\n");
30 fprintf(stderr, "\t-s: suspend <pid>\n");
31 exit(0);
32 }
33
34 int
35 main(int argc, char **argv)
36 {
37 int pid, err, i, ch;
38 unsigned int count;
39 mach_port_t task;
40 thread_act_array_t threads;
41 thread_precedence_policy_data_t policy;
42
43 boolean_t do_high = 0, do_resume = 0, do_suspend = 0;
44 boolean_t do_low = 1;
45
46 if (argc < 2)
47 usage();
48
49 while ((ch = getopt(argc, argv, "rsu")) != -1)
50 switch (ch) {
51 case 'u':
52 do_high = 1;
53 do_low = 0;
54 continue;
55 case 'r':
56 do_resume = 1;
57 do_low = 0;
58 continue;
59 case 's':
60 do_suspend = 1;
61 do_low = 0;
62 continue;
63 default:
64 usage();
65 }
66
67 argc -= optind; argv += optind;
68
69 if (argc == 0)
70 usage();
71
72 pid = atoi(*argv);
73 if (!pid)
74 usage();
75
76 err = task_for_pid(mach_task_self(), pid, &task);
77 if (err) {
78 fprintf(stderr, "Failed to get task port (%d)\n", err);
79 exit(0);
80 }
81
82 if (do_low || do_high) {
83
84 err = task_threads(task, &threads, &count);
85 if (err) {
86 fprintf(stderr, "Failed to get thread list (%d)\n", err);
87 exit(0);
88 }
89
90 if (do_low)
91 policy.importance = -100;
92 else
93 policy.importance = 0;
94
95 for (i = 0; i < count; i++) {
96 err = thread_policy_set(threads[i],
97 THREAD_PRECEDENCE_POLICY,
98 (thread_policy_t) &policy,
99 THREAD_PRECEDENCE_POLICY_COUNT);
100 if (err) {
101 fprintf(stderr, "Failed to set thread priority (%d)\n", err);
102 exit(0);
103 }
104 }
105
106 printf("Process %d's threads set to %s priority.\n", pid,
107 (do_low ? "lowest" : "highest"));
108 }
109
110 if (do_suspend) {
111 err = task_suspend(task);
112 if (err) {
113 fprintf(stderr, "Failed to suspend task (%d)\n", err);
114 } else {
115 printf("Process %d suspended.\n", pid);
116 }
117
118 }
119
120 if (do_resume) {
121 err = task_resume(task);
122 if (err) {
123 fprintf(stderr, "Failed to resume task (%d)\n", err);
124 } else {
125 printf("Process %d resumed.\n", pid);
126 }
127 }
128
129 return 0;
130 }
131