-static int cpu_count(void)
-{
- FILE* f;
- char buf[4096];
- int count = 0;
-
- f = fopen("/proc/stat", "r");
- if (f == NULL)
- return -1;
-
- while (fgets(buf, sizeof(buf), f) != NULL) {
- if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3]))
- count++;
- }
-
- fclose(f);
- if (count == 0)
- return -1;
- return count;
-}
-
-static int running_processes(void)
-{
- FILE* f;
- char buf[4096];
- int running = -1;
-
- f = fopen("/proc/stat", "r");
- if (f == NULL)
- return -1;
-
- while (fgets(buf, sizeof(buf), f) != NULL) {
- int value;
-
- if (sscanf(buf, "procs_running %u", &value) == 1) {
- running = value;
- break;
- }
- }
-
- fclose(f);
- return running;
-}
-
-/* return the number of process es in our session, count only until limit */
-static int running_processes_in_session(pid_t session, int limit)
-{
- DIR *dir;
- struct dirent *dent;
- int running = 0;
-
- dir = opendir("/proc");
- if (!dir)
- return -1;
-
- /* read process info from /proc */
- for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) {
- int f;
- char procdir[64];
- char line[256];
- const char *pos;
- char state;
- pid_t ppid, pgrp, sess;
- int len;
-
- if (!isdigit(dent->d_name[0]))
- continue;
-
- snprintf(procdir, sizeof(procdir), "/proc/%s/stat", dent->d_name);
- procdir[sizeof(procdir)-1] = '\0';
-
- f = open(procdir, O_RDONLY);
- if (f == -1)
- continue;
-
- len = read(f, line, sizeof(line)-1);
- close(f);
-
- if (len <= 0)
- continue;
- else
- line[len] = '\0';
-
- /* skip ugly program name */
- pos = strrchr(line, ')') + 2;
- if (pos == NULL)
- continue;
-
- if (sscanf(pos, "%c %d %d %d ", &state, &ppid, &pgrp, &sess) != 4)
- continue;
-
- /* count only processes in our session */
- if (sess != session)
- continue;
-
- /* count only running, no sleeping processes */
- if (state != 'R')
- continue;
-
- running++;
- if (limit > 0 && running >= limit)
- break;
- }
- closedir(dir);
-
- return running;
-}
-