+static int running_processes(void)
+{
+ int f;
+ static char buf[4096];
+ int len;
+ int running;
+ const char *pos;
+
+ f = open("/proc/stat", O_RDONLY);
+ if (f == -1)
+ return -1;
+
+ len = read(f, buf, sizeof(buf));
+ close(f);
+
+ if (len <= 0)
+ return -1;
+ else
+ buf[len] = '\0';
+
+ pos = strstr(buf, "procs_running ");
+ if (pos == NULL)
+ return -1;
+
+ if (sscanf(pos, "procs_running %u", &running) != 1)
+ return -1;
+
+ 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));
+ 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;
+}
+