/* * Moritz Orbach * Mo 21. Nov 00:21:03 CET 2011 * * GPL * gcc -Wall procinfo.c -o procinfo * * How to get nice value (priority) scheduler and real time priority of a * process in C (like chrt -p PID from util-linux) * * Don't forget to look at threads! "H" in top or something like * for i in $(ps -eLf| awk '$10 ~ /^hydrogen$/ { print $4 }'); do echo $i; ./procinfo $i; echo;done * * man getpriority * http://oreilly.com/catalog/linuxkernel/chapter/ch10.html#40766 * http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_setschedprio.html * http://pubs.opengroup.org/onlinepubs/009695399/functions/setpriority.html */ #include #include #include #include #include /* getpriority */ #include #include /* sched_getscheduler, sched_getparam */ #include /* schedulers */ #include typedef struct scheduler_t { int index; char *name[128]; /* int descht; */ } scheduler_t; /* from linux/sched.h */ static scheduler_t schedulers[] = { { SCHED_NORMAL, { "SCHED_NORMAL/SCHED_OTHER" } }, { SCHED_FIFO, { "SCHED_FIFO" } }, { SCHED_RR, { "SCHED_RR" } }, { SCHED_BATCH, { "SCHED_BATCH" } }, { SCHED_IDLE, { "SCHED_IDLE" } } }; /* * string to int * returns * 0 if string is no number * 1 success */ int s2int(char *str, int *number) { char *endptr; errno = 0; /* To distinguish success/failure after call */ *number = strtol(str, &endptr, 10); if (errno || *endptr != '\0') { if (errno) { perror("strtol"); } return 0; } return 1; } void usage(void) { printf("usage: procinfo PID\n"); } /* * nice value * * int getpriority(int which, int who); * int setpriority(int which, int who, int prio); */ int get_nice(pid_t pid, int *priority) { errno = 0; /* so says the man page. Why? */ *priority = getpriority(PRIO_PROCESS, pid); return errno == 0; } /* * int sched_getscheduler(pid_t pid); */ int get_schedpolicy(pid_t pid, int *algorithm) { *algorithm = sched_getscheduler(pid); return *algorithm != -1; } /* * int sched_getparam(pid_t pid, struct sched_param *param); */ int get_schedparams(pid_t pid, int *priority) { struct sched_param param; if (sched_getparam(pid, ¶m) != -1) { *priority = param.sched_priority; return 1; } else return 0; } /* * */ int main(int argc, char *argv[]) { pid_t pid; if (argc != 2) { usage(); return EXIT_FAILURE; } if (strcmp(argv[1], "-h") == 0) { usage(); return EXIT_SUCCESS; } if (!s2int(argv[1], &pid)) { usage(); return EXIT_FAILURE; } /* */ int nice; if (get_nice(pid, &nice)) printf("nice value\t: %d\n", nice); else { perror("getpriority"); return EXIT_FAILURE; } /* */ int scheduler; if (get_schedpolicy(pid, &scheduler)) printf("scheduler\t: %s (%d)\n", *schedulers[scheduler].name, scheduler); else { perror("sched_getscheduler"); return EXIT_FAILURE; } /* */ int priority; if (get_schedparams(pid, &priority)) printf("priority\t: %d\n", priority); else { perror("sched_getparam"); return EXIT_FAILURE; } /* printf("Other threads of this process may have other values!\n"); */ return EXIT_SUCCESS; }