// recursivity!!! void pid_store_cpu(unsigned index, unsigned parent, unsigned *utime, unsigned *stime) { if (pids[index].level == 1) { *utime = 0; *stime = 0; } // Remove unused parameter warning (void)parent; unsigned utmp = 0; unsigned stmp = 0; pid_get_cpu_time(index, &utmp, &stmp); *utime += utmp; *stime += stmp; unsigned i; for (i = index + 1; i < (unsigned)max_pids; i++) { if (pids[i].parent == (pid_t)index) pid_store_cpu(i, index, utime, stime); } if (pids[index].level == 1) { pids[index].utime = *utime; pids[index].stime = *stime; } }
// recursivity!!! void pid_store_cpu(unsigned index, unsigned parent, unsigned *utime, unsigned *stime) { if (pids[index].level == 1) { *utime = 0; *stime = 0; } unsigned utmp = 0; unsigned stmp = 0; pid_get_cpu_time(index, &utmp, &stmp); *utime += utmp; *stime += stmp; int i; for (i = index + 1; i < MAX_PIDS; i++) { if (pids[i].parent == index) pid_store_cpu(i, index, utime, stime); } if (pids[index].level == 1) { pids[index].utime = *utime; pids[index].stime = *stime; } }
void top(void) { if (getuid() == 0) firemon_drop_privs(); while (1) { // clear linked list head_clear(); // set pid table int i; int itv = 5; // 5 second interval pid_read(0); // start cpu measurements unsigned utime; unsigned stime; for (i = 0; i < MAX_PIDS; i++) { if (pids[i].level == 1) pid_store_cpu(i, 0, &utime, &stime); } // wait 5 seconds firemon_sleep(itv); // grab screen size struct winsize sz; int row = 24; int col = 80; if (!ioctl(0, TIOCGWINSZ, &sz)) { col = sz.ws_col; row = sz.ws_row; } // start printing firemon_clrscr(); char *header = get_header(); if (strlen(header) > col) header[col] = '\0'; printf("%s\n", header); if (row > 0) row--; free(header); // find system uptime FILE *fp = fopen("/proc/uptime", "r"); if (fp) { float f; int rv = fscanf(fp, "%f", &f); (void) rv; sysuptime = (unsigned long long) f; fclose(fp); } // print processes for (i = 0; i < MAX_PIDS; i++) { if (pids[i].level == 1) { float cpu = 0; int cnt = 0; // process count char *line = print_top(i, 0, &utime, &stime, itv, &cpu, &cnt); if (line) head_add(cpu, line); } } head_print(col, row); } }