]> git.saurik.com Git - apple/system_cmds.git/blob - mean.tproj/mean.c
9e5601810b819e7face057cf319d5a04a37c00bd
[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 Apple Inc. All rights reserved.
7 *
8 */
9
10 #include <mach/mach.h>
11 #include <mach/task.h>
12
13 #include <sys/resource.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 #ifndef PRIO_DARWIN_PROCESS
23 #define PRIO_DARWIN_PROCESS 4 /* Second argument is a PID */
24 #endif
25
26 void
27 usage(void)
28 {
29 fprintf(stderr, "Usage: mean -t <pid>\n");
30 fprintf(stderr, "\tthrottle <pid>'s usage of cpu, I/O, and networking\n");
31 fprintf(stderr, "mean -u <pid>\n");
32 fprintf(stderr, "\treturn <pid> to normal priority\n");
33 fprintf(stderr, "mean -[s|r] <pid>\n");
34 fprintf(stderr, "\tsuspend or resume <pid>\n");
35 exit(0);
36 }
37
38 int
39 main(int argc, char **argv)
40 {
41 int pid, err, ch;
42 mach_port_t task;
43 int priority = 0;
44
45 boolean_t do_resume = 0, do_suspend = 0;
46 boolean_t do_throttle = 0, do_undo = 0;
47
48 if (argc < 2)
49 usage();
50
51 while ((ch = getopt(argc, argv, "rstu")) != -1)
52 switch (ch) {
53 case 'u':
54 do_undo = 1;
55 continue;
56 case 'r':
57 do_resume = 1;
58 continue;
59 case 's':
60 do_suspend = 1;
61 continue;
62 case 't':
63 do_throttle = 1;
64 continue;
65 default:
66 usage();
67 }
68
69 argc -= optind; argv += optind;
70
71 if (argc == 0)
72 usage();
73
74 pid = atoi(*argv);
75 if (!pid)
76 usage();
77
78 if (do_throttle || do_undo) {
79 priority = PRIO_DARWIN_BG;
80
81 if (do_undo)
82 priority = 0;
83
84 err = setpriority(PRIO_DARWIN_PROCESS, pid, priority);
85 if (err) {
86 fprintf(stderr, "Failed to set priority (%d)\n", errno);
87 exit(0);
88 }
89 }
90
91 if (do_suspend || do_resume) {
92 err = task_for_pid(mach_task_self(), pid, &task);
93 if (err) {
94 fprintf(stderr, "Failed to get task port (%d)\n", err);
95 exit(0);
96 }
97
98 if (do_suspend) {
99 err = task_suspend(task);
100 if (err) {
101 fprintf(stderr, "Failed to suspend task (%d)\n", err);
102 }
103
104 }
105
106 if (do_resume) {
107 err = task_resume(task);
108 if (err) {
109 fprintf(stderr, "Failed to resume task (%d)\n", err);
110 }
111 }
112 }
113
114 return 0;
115 }
116