1 /* -*- mode: c; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
3 * Conky, a system monitor, based on torsmo
5 * Any original torsmo code is licensed under the BSD license
7 * All code written since the fork of torsmo is licensed under the GPL
9 * Please see COPYING for details
11 * Copyright (c) 2005 Adi Zaimi, Dan Piponi <dan@tanelorn.demon.co.uk>,
12 * Dave Clark <clarkd@skynet.ca>
13 * Copyright (c) 2005-2009 Brenden Matthews, Philip Kovacs, et. al.
15 * All rights reserved.
17 * This program is free software: you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation, either version 3 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 * You should have received a copy of the GNU General Public License
27 * along with this program. If not, see <http://www.gnu.org/licenses/>.
29 * vim: ts=4 sw=4 noet ai cindent syntax=c
36 static unsigned long g_time = 0;
37 static unsigned long long previous_total = 0;
38 static struct process *first_process = 0;
40 struct process *get_first_process(void)
45 void free_all_processes(void)
47 struct process *next = NULL, *pr = first_process;
60 struct process *get_process_by_name(const char *name)
62 struct process *p = first_process;
65 if (!strcmp(p->name, name))
72 static struct process *find_process(pid_t pid)
74 struct process *p = first_process;
85 /* Create a new process object and insert it into the process list */
86 static struct process *new_process(int p)
88 struct process *process;
89 process = (struct process *) malloc(sizeof(struct process));
91 // clean up memory first
92 memset(process, 0, sizeof(struct process));
94 /* Do stitching necessary for doubly linked list */
96 process->previous = 0;
97 process->next = first_process;
99 process->next->previous = process;
101 first_process = process;
104 process->time_stamp = 0;
105 process->previous_user_time = ULONG_MAX;
106 process->previous_kernel_time = ULONG_MAX;
108 process->previous_read_bytes = ULLONG_MAX;
109 process->previous_write_bytes = ULLONG_MAX;
111 process->counted = 1;
113 /* process_find_name(process); */
118 /******************************************
120 ******************************************/
122 /******************************************
123 * Extract information from /proc *
124 ******************************************/
126 /* These are the guts that extract information out of /proc.
127 * Anyone hoping to port wmtop should look here first. */
128 static int process_parse_stat(struct process *process)
130 struct information *cur = &info;
131 char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN], procname[BUFFER_LEN];
133 unsigned long user_time = 0;
134 unsigned long kernel_time = 0;
139 char *lparen, *rparen;
141 snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid);
143 ps = open(filename, O_RDONLY);
145 /* The process must have finished in the last few jiffies! */
149 /* Mark process as up-to-date. */
150 process->time_stamp = g_time;
152 rc = read(ps, line, sizeof(line));
158 /* Extract cpu times from data in /proc filesystem */
159 lparen = strchr(line, '(');
160 rparen = strrchr(line, ')');
161 if(!lparen || !rparen || rparen < lparen)
162 return 1; // this should not happen
164 rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1);
165 strncpy(procname, lparen + 1, rc);
167 rc = sscanf(rparen + 1, "%*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu "
168 "%lu %*s %*s %*s %d %*s %*s %*s %u %u", &process->user_time,
169 &process->kernel_time, &nice_val, &process->vsize, &process->rss);
173 /* remove any "kdeinit: " */
174 if (procname == strstr(procname, "kdeinit")) {
175 snprintf(filename, sizeof(filename), PROCFS_CMDLINE_TEMPLATE,
178 ps = open(filename, O_RDONLY);
180 /* The process must have finished in the last few jiffies! */
184 endl = read(ps, line, sizeof(line));
187 /* null terminate the input */
189 /* account for "kdeinit: " */
190 if ((char *) line == strstr(line, "kdeinit: ")) {
191 r = ((char *) line) + 9;
198 while (*r && *r != ' ') {
207 process->name = strndup(procname, text_buffer_size);
208 process->rss *= getpagesize();
211 update_total_processes();
214 process->total_cpu_time = process->user_time + process->kernel_time;
215 process->totalmem = (float) (((float) process->rss / cur->memmax) / 10);
216 if (process->previous_user_time == ULONG_MAX) {
217 process->previous_user_time = process->user_time;
219 if (process->previous_kernel_time == ULONG_MAX) {
220 process->previous_kernel_time = process->kernel_time;
223 /* store the difference of the user_time */
224 user_time = process->user_time - process->previous_user_time;
225 kernel_time = process->kernel_time - process->previous_kernel_time;
227 /* backup the process->user_time for next time around */
228 process->previous_user_time = process->user_time;
229 process->previous_kernel_time = process->kernel_time;
231 /* store only the difference of the user_time here... */
232 process->user_time = user_time;
233 process->kernel_time = kernel_time;
239 static int process_parse_io(struct process *process)
241 static const char *read_bytes_str="read_bytes:";
242 static const char *write_bytes_str="write_bytes:";
244 char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN];
248 unsigned long long read_bytes, write_bytes;
250 snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid);
252 ps = open(filename, O_RDONLY);
254 /* The process must have finished in the last few jiffies!
255 * Or, the kernel doesn't support I/O accounting.
260 rc = read(ps, line, sizeof(line));
266 pos = strstr(line, read_bytes_str);
268 /* these should not happen (unless the format of the file changes) */
271 pos += strlen(read_bytes_str);
272 process->read_bytes = strtoull(pos, &endpos, 10);
277 pos = strstr(line, write_bytes_str);
281 pos += strlen(write_bytes_str);
282 process->write_bytes = strtoull(pos, &endpos, 10);
287 if (process->previous_read_bytes == ULLONG_MAX) {
288 process->previous_read_bytes = process->read_bytes;
290 if (process->previous_write_bytes == ULLONG_MAX) {
291 process->previous_write_bytes = process->write_bytes;
294 /* store the difference of the byte counts */
295 read_bytes = process->read_bytes - process->previous_read_bytes;
296 write_bytes = process->write_bytes - process->previous_write_bytes;
298 /* backup the counts for next time around */
299 process->previous_read_bytes = process->read_bytes;
300 process->previous_write_bytes = process->write_bytes;
302 /* store only the difference here... */
303 process->read_bytes = read_bytes;
304 process->write_bytes = write_bytes;
310 /******************************************
311 * Get process structure for process pid *
312 ******************************************/
314 /* This function seems to hog all of the CPU time.
315 * I can't figure out why - it doesn't do much. */
316 static int calculate_stats(struct process *process)
320 /* compute each process cpu usage by reading /proc/<proc#>/stat */
321 rc = process_parse_stat(process);
323 /* rc = process_parse_statm(process); if (rc) return 1; */
326 rc = process_parse_io(process);
331 * Check name against the exclusion list
333 /* if (process->counted && exclusion_expression &&
334 * !regexec(exclusion_expression, process->name, 0, 0, 0))
335 * process->counted = 0; */
340 /******************************************
341 * Update process table *
342 ******************************************/
344 static int update_process_table(void)
347 struct dirent *entry;
349 if (!(dir = opendir("/proc"))) {
355 /* Get list of processes from /proc directory */
356 while ((entry = readdir(dir))) {
360 /* Problem reading list of processes */
365 if (sscanf(entry->d_name, "%d", &pid) > 0) {
368 p = find_process(pid);
370 p = new_process(pid);
373 /* compute each process cpu usage */
383 /******************************************
384 * Destroy and remove a process *
385 ******************************************/
387 static void delete_process(struct process *p)
389 #if defined(PARANOID)
390 assert(p->id == 0x0badfeed);
393 * Ensure that deleted processes aren't reused.
396 #endif /* defined(PARANOID) */
399 * Maintain doubly linked list.
402 p->next->previous = p->previous;
404 p->previous->next = p->next;
406 first_process = p->next;
414 /******************************************
415 * Strip dead process entries *
416 ******************************************/
418 static void process_cleanup(void)
421 struct process *p = first_process;
424 struct process *current = p;
426 #if defined(PARANOID)
427 assert(p->id == 0x0badfeed);
428 #endif /* defined(PARANOID) */
431 /* Delete processes that have died */
432 if (current->time_stamp != g_time) {
433 delete_process(current);
438 /******************************************
439 * Calculate cpu total *
440 ******************************************/
441 #define TMPL_SHORTPROC "%*s %llu %llu %llu %llu"
442 #define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu"
444 static unsigned long long calc_cpu_total(void)
446 unsigned long long total = 0;
447 unsigned long long t = 0;
450 char line[BUFFER_LEN] = { 0 };
451 unsigned long long cpu = 0;
452 unsigned long long niceval = 0;
453 unsigned long long systemval = 0;
454 unsigned long long idle = 0;
455 unsigned long long iowait = 0;
456 unsigned long long irq = 0;
457 unsigned long long softirq = 0;
458 unsigned long long steal = 0;
459 const char *template =
460 KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC;
462 ps = open("/proc/stat", O_RDONLY);
463 rc = read(ps, line, sizeof(line));
469 sscanf(line, template, &cpu, &niceval, &systemval, &idle, &iowait, &irq,
471 total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal;
473 t = total - previous_total;
474 previous_total = total;
479 /******************************************
480 * Calculate each processes cpu *
481 ******************************************/
483 inline static void calc_cpu_each(unsigned long long total)
485 struct process *p = first_process;
488 p->amount = 100.0 * (cpu_separate ? info.cpu_count : 1) *
489 (p->user_time + p->kernel_time) / (float) total;
496 static void calc_io_each(void)
499 unsigned long long sum = 0;
501 for (p = first_process; p; p = p->next)
502 sum += p->read_bytes + p->write_bytes;
505 sum = 1; /* to avoid having NANs if no I/O occured */
506 for (p = first_process; p; p = p->next)
507 p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float) sum;
511 /******************************************
512 * Find the top processes *
513 ******************************************/
515 /* free a sp_process structure */
516 static void free_sp(struct sorted_process *sp)
521 /* create a new sp_process structure */
522 static struct sorted_process *malloc_sp(struct process *proc)
524 struct sorted_process *sp;
525 sp = malloc(sizeof(struct sorted_process));
532 /* cpu comparison function for insert_sp_element */
533 static int compare_cpu(struct process *a, struct process *b)
535 if (a->amount < b->amount) {
537 } else if (a->amount > b->amount) {
544 /* mem comparison function for insert_sp_element */
545 static int compare_mem(struct process *a, struct process *b)
547 if (a->totalmem < b->totalmem) {
549 } else if (a->totalmem > b->totalmem) {
556 /* CPU time comparision function for insert_sp_element */
557 static int compare_time(struct process *a, struct process *b)
559 return b->total_cpu_time - a->total_cpu_time;
563 /* I/O comparision function for insert_sp_element */
564 static int compare_io(struct process *a, struct process *b)
566 if (a->io_perc < b->io_perc) {
568 } else if (a->io_perc > b->io_perc) {
576 /* insert this process into the list in a sorted fashion,
577 * or destroy it if it doesn't fit on the list */
578 static int insert_sp_element(struct sorted_process *sp_cur,
579 struct sorted_process **p_sp_head, struct sorted_process **p_sp_tail,
580 int max_elements, int compare_funct(struct process *, struct process *))
583 struct sorted_process *sp_readthru = NULL, *sp_destroy = NULL;
584 int did_insert = 0, x = 0;
586 if (*p_sp_head == NULL) {
591 for (sp_readthru = *p_sp_head, x = 0;
592 sp_readthru != NULL && x < max_elements;
593 sp_readthru = sp_readthru->less, x++) {
594 if (compare_funct(sp_readthru->proc, sp_cur->proc) > 0 && !did_insert) {
595 /* sp_cur is bigger than sp_readthru
596 * so insert it before sp_readthru */
597 sp_cur->less = sp_readthru;
598 if (sp_readthru == *p_sp_head) {
599 /* insert as the new head of the list */
602 /* insert inside the list */
603 sp_readthru->greater->less = sp_cur;
604 sp_cur->greater = sp_readthru->greater;
606 sp_readthru->greater = sp_cur;
607 /* element was inserted, so increase the counter */
611 if (x < max_elements && sp_readthru == NULL && !did_insert) {
612 /* sp_cur is the smallest element and list isn't full,
613 * so insert at the end */
614 (*p_sp_tail)->less = sp_cur;
615 sp_cur->greater = *p_sp_tail;
618 } else if (x >= max_elements) {
619 /* We inserted an element and now the list is too big by one.
620 * Destroy the smallest element */
621 sp_destroy = *p_sp_tail;
622 *p_sp_tail = sp_destroy->greater;
623 (*p_sp_tail)->less = NULL;
627 /* sp_cur wasn't added to the sorted list, so destroy it */
633 /* copy the procs in the sorted list to the array, and destroy the list */
634 static void sp_acopy(struct sorted_process *sp_head, struct process **ar, int max_size)
636 struct sorted_process *sp_cur, *sp_tmp;
640 for (x = 0; x < max_size && sp_cur != NULL; x++) {
641 ar[x] = sp_cur->proc;
643 sp_cur = sp_cur->less;
648 /* ****************************************************************** *
649 * Get a sorted list of the top cpu hogs and top mem hogs. *
650 * Results are stored in the cpu,mem arrays in decreasing order[0-9]. *
651 * ****************************************************************** */
653 void process_find_top(struct process **cpu, struct process **mem,
654 struct process **ptime
656 , struct process **io
660 struct sorted_process *spc_head = NULL, *spc_tail = NULL, *spc_cur = NULL;
661 struct sorted_process *spm_head = NULL, *spm_tail = NULL, *spm_cur = NULL;
662 struct sorted_process *spt_head = NULL, *spt_tail = NULL, *spt_cur = NULL;
664 struct sorted_process *spi_head = NULL, *spi_tail = NULL, *spi_cur = NULL;
666 struct process *cur_proc = NULL;
667 unsigned long long total = 0;
669 if (!top_cpu && !top_mem && !top_time
678 total = calc_cpu_total(); /* calculate the total of the processor */
679 update_process_table(); /* update the table with process list */
680 calc_cpu_each(total); /* and then the percentage for each task */
681 process_cleanup(); /* cleanup list from exited processes */
683 calc_io_each(); /* percentage of I/O for each task */
686 cur_proc = first_process;
688 while (cur_proc != NULL) {
690 spc_cur = malloc_sp(cur_proc);
691 insert_sp_element(spc_cur, &spc_head, &spc_tail, MAX_SP,
695 spm_cur = malloc_sp(cur_proc);
696 insert_sp_element(spm_cur, &spm_head, &spm_tail, MAX_SP,
700 spt_cur = malloc_sp(cur_proc);
701 insert_sp_element(spt_cur, &spt_head, &spt_tail, MAX_SP,
706 spi_cur = malloc_sp(cur_proc);
707 insert_sp_element(spi_cur, &spi_head, &spi_tail, MAX_SP,
711 cur_proc = cur_proc->next;
714 if (top_cpu) sp_acopy(spc_head, cpu, MAX_SP);
715 if (top_mem) sp_acopy(spm_head, mem, MAX_SP);
716 if (top_time) sp_acopy(spt_head, ptime, MAX_SP);
718 if (top_io) sp_acopy(spi_head, io, MAX_SP);
722 int parse_top_args(const char *s, const char *arg, struct text_object *obj)
727 if (obj->data.top.was_parsed) {
730 obj->data.top.was_parsed = 1;
732 if (arg && !obj->data.top.s) {
733 obj->data.top.s = strndup(arg, text_buffer_size);
739 } else if (strcmp(&s[3], "_mem") == EQUAL) {
740 obj->type = OBJ_top_mem;
742 } else if (strcmp(&s[3], "_time") == EQUAL) {
743 obj->type = OBJ_top_time;
746 } else if (strcmp(&s[3], "_io") == EQUAL) {
747 obj->type = OBJ_top_io;
752 NORM_ERR("Must be top, top_mem, top_time or top_io");
754 NORM_ERR("Must be top, top_mem or top_time");
760 NORM_ERR("top needs arguments");
764 if (sscanf(arg, "%63s %i", buf, &n) == 2) {
765 if (strcmp(buf, "name") == EQUAL) {
766 obj->data.top.type = TOP_NAME;
767 } else if (strcmp(buf, "cpu") == EQUAL) {
768 obj->data.top.type = TOP_CPU;
769 } else if (strcmp(buf, "pid") == EQUAL) {
770 obj->data.top.type = TOP_PID;
771 } else if (strcmp(buf, "mem") == EQUAL) {
772 obj->data.top.type = TOP_MEM;
773 } else if (strcmp(buf, "time") == EQUAL) {
774 obj->data.top.type = TOP_TIME;
775 } else if (strcmp(buf, "mem_res") == EQUAL) {
776 obj->data.top.type = TOP_MEM_RES;
777 } else if (strcmp(buf, "mem_vsize") == EQUAL) {
778 obj->data.top.type = TOP_MEM_VSIZE;
780 } else if (strcmp(buf, "io_read") == EQUAL) {
781 obj->data.top.type = TOP_READ_BYTES;
782 } else if (strcmp(buf, "io_write") == EQUAL) {
783 obj->data.top.type = TOP_WRITE_BYTES;
784 } else if (strcmp(buf, "io_perc") == EQUAL) {
785 obj->data.top.type = TOP_IO_PERC;
788 NORM_ERR("invalid type arg for top");
790 NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize, "
791 "io_read, io_write, io_perc");
793 NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize");
797 if (n < 1 || n > 10) {
798 NORM_ERR("invalid num arg for top. Must be between 1 and 10.");
801 obj->data.top.num = n - 1;
804 NORM_ERR("invalid argument count for top");