1 /* -*- mode: c; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
2 * vim: ts=4 sw=4 noet ai cindent syntax=c
4 * Conky, a system monitor, based on torsmo
6 * Any original torsmo code is licensed under the BSD license
8 * All code written since the fork of torsmo is licensed under the GPL
10 * Please see COPYING for details
12 * Copyright (c) 2005 Adi Zaimi, Dan Piponi <dan@tanelorn.demon.co.uk>,
13 * Dave Clark <clarkd@skynet.ca>
14 * Copyright (c) 2005-2009 Brenden Matthews, Philip Kovacs, et. al.
16 * All rights reserved.
18 * This program is free software: you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation, either version 3 of the License, or
21 * (at your option) any later version.
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 static unsigned long g_time = 0;
36 static unsigned long long previous_total = 0;
37 static struct process *first_process = 0;
39 /* a simple hash table to speed up find_process() */
40 struct proc_hash_entry {
41 struct proc_hash_entry *next;
44 static struct proc_hash_entry proc_hash_table[256];
46 static void hash_process(struct process *p)
48 struct proc_hash_entry *phe;
49 static char first_run = 1;
51 /* better make sure all next pointers are zero upon first access */
53 memset(proc_hash_table, 0, sizeof(struct proc_hash_entry) * 256);
57 /* get the bucket head */
58 phe = &proc_hash_table[p->pid % 256];
60 /* find the bucket's end */
65 phe->next = malloc(sizeof(struct proc_hash_entry));
66 memset(phe->next, 0, sizeof(struct proc_hash_entry));
70 static void unhash_process(struct process *p)
72 struct proc_hash_entry *phe, *tmp;
74 /* get the bucket head */
75 phe = &proc_hash_table[p->pid % 256];
77 /* find the entry pointing to p and drop it */
79 if (phe->next->proc == p) {
81 phe->next = phe->next->next;
89 static void __unhash_all_processes(struct proc_hash_entry *phe)
92 __unhash_all_processes(phe->next);
96 static void unhash_all_processes(void)
100 for (i = 0; i < 256; i++) {
101 __unhash_all_processes(&proc_hash_table[i]);
102 proc_hash_table[i].next = NULL;
106 struct process *get_first_process(void)
108 return first_process;
111 void free_all_processes(void)
113 struct process *next = NULL, *pr = first_process;
123 first_process = NULL;
125 /* drop the whole hash table */
126 unhash_all_processes();
129 struct process *get_process_by_name(const char *name)
131 struct process *p = first_process;
134 if (!strcmp(p->name, name))
141 static struct process *find_process(pid_t pid)
143 struct proc_hash_entry *phe;
145 phe = &proc_hash_table[pid % 256];
147 if (phe->next->proc->pid == pid)
148 return phe->next->proc;
154 /* Create a new process object and insert it into the process list */
155 static struct process *new_process(int p)
157 struct process *process;
158 process = (struct process *) malloc(sizeof(struct process));
160 // clean up memory first
161 memset(process, 0, sizeof(struct process));
163 /* Do stitching necessary for doubly linked list */
165 process->previous = 0;
166 process->next = first_process;
168 process->next->previous = process;
170 first_process = process;
173 process->time_stamp = 0;
174 process->previous_user_time = ULONG_MAX;
175 process->previous_kernel_time = ULONG_MAX;
177 process->previous_read_bytes = ULLONG_MAX;
178 process->previous_write_bytes = ULLONG_MAX;
180 process->counted = 1;
182 /* process_find_name(process); */
184 /* add the process to the hash table */
185 hash_process(process);
190 /******************************************
192 ******************************************/
194 /******************************************
195 * Extract information from /proc *
196 ******************************************/
198 /* These are the guts that extract information out of /proc.
199 * Anyone hoping to port wmtop should look here first. */
200 static int process_parse_stat(struct process *process)
202 struct information *cur = &info;
203 char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN], procname[BUFFER_LEN];
205 unsigned long user_time = 0;
206 unsigned long kernel_time = 0;
211 char *lparen, *rparen;
213 snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid);
215 ps = open(filename, O_RDONLY);
217 /* The process must have finished in the last few jiffies! */
221 /* Mark process as up-to-date. */
222 process->time_stamp = g_time;
224 rc = read(ps, line, sizeof(line));
230 /* Extract cpu times from data in /proc filesystem */
231 lparen = strchr(line, '(');
232 rparen = strrchr(line, ')');
233 if(!lparen || !rparen || rparen < lparen)
234 return 1; // this should not happen
236 rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1);
237 strncpy(procname, lparen + 1, rc);
239 rc = sscanf(rparen + 1, "%*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu "
240 "%lu %*s %*s %*s %d %*s %*s %*s %u %u", &process->user_time,
241 &process->kernel_time, &nice_val, &process->vsize, &process->rss);
243 NORM_ERR("scaning data for %s failed, got only %d fields", procname, rc);
246 /* remove any "kdeinit: " */
247 if (procname == strstr(procname, "kdeinit")) {
248 snprintf(filename, sizeof(filename), PROCFS_CMDLINE_TEMPLATE,
251 ps = open(filename, O_RDONLY);
253 /* The process must have finished in the last few jiffies! */
257 endl = read(ps, line, sizeof(line));
260 /* null terminate the input */
262 /* account for "kdeinit: " */
263 if ((char *) line == strstr(line, "kdeinit: ")) {
264 r = ((char *) line) + 9;
271 while (*r && *r != ' ') {
280 process->name = strndup(procname, text_buffer_size);
281 process->rss *= getpagesize();
284 update_total_processes();
287 process->total_cpu_time = process->user_time + process->kernel_time;
288 process->totalmem = (float) (((float) process->rss / cur->memmax) / 10);
289 if (process->previous_user_time == ULONG_MAX) {
290 process->previous_user_time = process->user_time;
292 if (process->previous_kernel_time == ULONG_MAX) {
293 process->previous_kernel_time = process->kernel_time;
296 /* strangely, the values aren't monotonous */
297 if (process->previous_user_time > process->user_time)
298 process->previous_user_time = process->user_time;
300 if (process->previous_kernel_time > process->kernel_time)
301 process->previous_kernel_time = process->kernel_time;
303 /* store the difference of the user_time */
304 user_time = process->user_time - process->previous_user_time;
305 kernel_time = process->kernel_time - process->previous_kernel_time;
307 /* backup the process->user_time for next time around */
308 process->previous_user_time = process->user_time;
309 process->previous_kernel_time = process->kernel_time;
311 /* store only the difference of the user_time here... */
312 process->user_time = user_time;
313 process->kernel_time = kernel_time;
319 static int process_parse_io(struct process *process)
321 static const char *read_bytes_str="read_bytes:";
322 static const char *write_bytes_str="write_bytes:";
324 char line[BUFFER_LEN] = { 0 }, filename[BUFFER_LEN];
328 unsigned long long read_bytes, write_bytes;
330 snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid);
332 ps = open(filename, O_RDONLY);
334 /* The process must have finished in the last few jiffies!
335 * Or, the kernel doesn't support I/O accounting.
340 rc = read(ps, line, sizeof(line));
346 pos = strstr(line, read_bytes_str);
348 /* these should not happen (unless the format of the file changes) */
351 pos += strlen(read_bytes_str);
352 process->read_bytes = strtoull(pos, &endpos, 10);
357 pos = strstr(line, write_bytes_str);
361 pos += strlen(write_bytes_str);
362 process->write_bytes = strtoull(pos, &endpos, 10);
367 if (process->previous_read_bytes == ULLONG_MAX) {
368 process->previous_read_bytes = process->read_bytes;
370 if (process->previous_write_bytes == ULLONG_MAX) {
371 process->previous_write_bytes = process->write_bytes;
374 /* store the difference of the byte counts */
375 read_bytes = process->read_bytes - process->previous_read_bytes;
376 write_bytes = process->write_bytes - process->previous_write_bytes;
378 /* backup the counts for next time around */
379 process->previous_read_bytes = process->read_bytes;
380 process->previous_write_bytes = process->write_bytes;
382 /* store only the difference here... */
383 process->read_bytes = read_bytes;
384 process->write_bytes = write_bytes;
390 /******************************************
391 * Get process structure for process pid *
392 ******************************************/
394 /* This function seems to hog all of the CPU time.
395 * I can't figure out why - it doesn't do much. */
396 static int calculate_stats(struct process *process)
400 /* compute each process cpu usage by reading /proc/<proc#>/stat */
401 rc = process_parse_stat(process);
403 /* rc = process_parse_statm(process); if (rc) return 1; */
406 rc = process_parse_io(process);
411 * Check name against the exclusion list
413 /* if (process->counted && exclusion_expression &&
414 * !regexec(exclusion_expression, process->name, 0, 0, 0))
415 * process->counted = 0; */
420 /******************************************
421 * Update process table *
422 ******************************************/
424 static int update_process_table(void)
427 struct dirent *entry;
429 if (!(dir = opendir("/proc"))) {
435 /* Get list of processes from /proc directory */
436 while ((entry = readdir(dir))) {
440 /* Problem reading list of processes */
445 if (sscanf(entry->d_name, "%d", &pid) > 0) {
448 p = find_process(pid);
450 p = new_process(pid);
453 /* compute each process cpu usage */
463 /******************************************
464 * Destroy and remove a process *
465 ******************************************/
467 static void delete_process(struct process *p)
469 #if defined(PARANOID)
470 assert(p->id == 0x0badfeed);
473 * Ensure that deleted processes aren't reused.
476 #endif /* defined(PARANOID) */
479 * Maintain doubly linked list.
482 p->next->previous = p->previous;
484 p->previous->next = p->next;
486 first_process = p->next;
491 /* remove the process from the hash table */
496 /******************************************
497 * Strip dead process entries *
498 ******************************************/
500 static void process_cleanup(void)
503 struct process *p = first_process;
506 struct process *current = p;
508 #if defined(PARANOID)
509 assert(p->id == 0x0badfeed);
510 #endif /* defined(PARANOID) */
513 /* Delete processes that have died */
514 if (current->time_stamp != g_time) {
515 delete_process(current);
520 /******************************************
521 * Calculate cpu total *
522 ******************************************/
523 #define TMPL_SHORTPROC "%*s %llu %llu %llu %llu"
524 #define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu"
526 static unsigned long long calc_cpu_total(void)
528 unsigned long long total = 0;
529 unsigned long long t = 0;
532 char line[BUFFER_LEN] = { 0 };
533 unsigned long long cpu = 0;
534 unsigned long long niceval = 0;
535 unsigned long long systemval = 0;
536 unsigned long long idle = 0;
537 unsigned long long iowait = 0;
538 unsigned long long irq = 0;
539 unsigned long long softirq = 0;
540 unsigned long long steal = 0;
541 const char *template =
542 KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC;
544 ps = open("/proc/stat", O_RDONLY);
545 rc = read(ps, line, sizeof(line));
551 sscanf(line, template, &cpu, &niceval, &systemval, &idle, &iowait, &irq,
553 total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal;
555 t = total - previous_total;
556 previous_total = total;
561 /******************************************
562 * Calculate each processes cpu *
563 ******************************************/
565 inline static void calc_cpu_each(unsigned long long total)
567 struct process *p = first_process;
570 p->amount = 100.0 * (cpu_separate ? info.cpu_count : 1) *
571 (p->user_time + p->kernel_time) / (float) total;
578 static void calc_io_each(void)
581 unsigned long long sum = 0;
583 for (p = first_process; p; p = p->next)
584 sum += p->read_bytes + p->write_bytes;
587 sum = 1; /* to avoid having NANs if no I/O occured */
588 for (p = first_process; p; p = p->next)
589 p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float) sum;
593 /******************************************
594 * Find the top processes *
595 ******************************************/
597 /* free a sp_process structure */
598 static void free_sp(struct sorted_process *sp)
603 /* create a new sp_process structure */
604 static struct sorted_process *malloc_sp(struct process *proc)
606 struct sorted_process *sp;
607 sp = malloc(sizeof(struct sorted_process));
608 memset(sp, 0, sizeof(struct sorted_process));
613 /* cpu comparison function for insert_sp_element */
614 static int compare_cpu(struct process *a, struct process *b)
616 if (a->amount < b->amount) {
618 } else if (a->amount > b->amount) {
625 /* mem comparison function for insert_sp_element */
626 static int compare_mem(struct process *a, struct process *b)
628 if (a->totalmem < b->totalmem) {
630 } else if (a->totalmem > b->totalmem) {
637 /* CPU time comparision function for insert_sp_element */
638 static int compare_time(struct process *a, struct process *b)
640 return b->total_cpu_time - a->total_cpu_time;
644 /* I/O comparision function for insert_sp_element */
645 static int compare_io(struct process *a, struct process *b)
647 if (a->io_perc < b->io_perc) {
649 } else if (a->io_perc > b->io_perc) {
657 /* insert this process into the list in a sorted fashion,
658 * or destroy it if it doesn't fit on the list */
659 static int insert_sp_element(struct sorted_process *sp_cur,
660 struct sorted_process **p_sp_head, struct sorted_process **p_sp_tail,
661 int max_elements, int compare_funct(struct process *, struct process *))
664 struct sorted_process *sp_readthru = NULL, *sp_destroy = NULL;
665 int did_insert = 0, x = 0;
667 if (*p_sp_head == NULL) {
672 for (sp_readthru = *p_sp_head, x = 0;
673 sp_readthru != NULL && x < max_elements;
674 sp_readthru = sp_readthru->less, x++) {
675 if (compare_funct(sp_readthru->proc, sp_cur->proc) > 0 && !did_insert) {
676 /* sp_cur is bigger than sp_readthru
677 * so insert it before sp_readthru */
678 sp_cur->less = sp_readthru;
679 if (sp_readthru == *p_sp_head) {
680 /* insert as the new head of the list */
683 /* insert inside the list */
684 sp_readthru->greater->less = sp_cur;
685 sp_cur->greater = sp_readthru->greater;
687 sp_readthru->greater = sp_cur;
688 /* element was inserted, so increase the counter */
692 if (x < max_elements && sp_readthru == NULL && !did_insert) {
693 /* sp_cur is the smallest element and list isn't full,
694 * so insert at the end */
695 (*p_sp_tail)->less = sp_cur;
696 sp_cur->greater = *p_sp_tail;
699 } else if (x >= max_elements) {
700 /* We inserted an element and now the list is too big by one.
701 * Destroy the smallest element */
702 sp_destroy = *p_sp_tail;
703 *p_sp_tail = sp_destroy->greater;
704 (*p_sp_tail)->less = NULL;
708 /* sp_cur wasn't added to the sorted list, so destroy it */
714 /* copy the procs in the sorted list to the array, and destroy the list */
715 static void sp_acopy(struct sorted_process *sp_head, struct process **ar, int max_size)
717 struct sorted_process *sp_cur, *sp_tmp;
721 for (x = 0; x < max_size && sp_cur != NULL; x++) {
722 ar[x] = sp_cur->proc;
724 sp_cur = sp_cur->less;
729 /* ****************************************************************** *
730 * Get a sorted list of the top cpu hogs and top mem hogs. *
731 * Results are stored in the cpu,mem arrays in decreasing order[0-9]. *
732 * ****************************************************************** */
734 void process_find_top(struct process **cpu, struct process **mem,
735 struct process **ptime
737 , struct process **io
741 struct sorted_process *spc_head = NULL, *spc_tail = NULL, *spc_cur = NULL;
742 struct sorted_process *spm_head = NULL, *spm_tail = NULL, *spm_cur = NULL;
743 struct sorted_process *spt_head = NULL, *spt_tail = NULL, *spt_cur = NULL;
745 struct sorted_process *spi_head = NULL, *spi_tail = NULL, *spi_cur = NULL;
747 struct process *cur_proc = NULL;
748 unsigned long long total = 0;
750 if (!top_cpu && !top_mem && !top_time
759 total = calc_cpu_total(); /* calculate the total of the processor */
760 update_process_table(); /* update the table with process list */
761 calc_cpu_each(total); /* and then the percentage for each task */
762 process_cleanup(); /* cleanup list from exited processes */
764 calc_io_each(); /* percentage of I/O for each task */
767 cur_proc = first_process;
769 while (cur_proc != NULL) {
771 spc_cur = malloc_sp(cur_proc);
772 insert_sp_element(spc_cur, &spc_head, &spc_tail, MAX_SP,
776 spm_cur = malloc_sp(cur_proc);
777 insert_sp_element(spm_cur, &spm_head, &spm_tail, MAX_SP,
781 spt_cur = malloc_sp(cur_proc);
782 insert_sp_element(spt_cur, &spt_head, &spt_tail, MAX_SP,
787 spi_cur = malloc_sp(cur_proc);
788 insert_sp_element(spi_cur, &spi_head, &spi_tail, MAX_SP,
792 cur_proc = cur_proc->next;
795 if (top_cpu) sp_acopy(spc_head, cpu, MAX_SP);
796 if (top_mem) sp_acopy(spm_head, mem, MAX_SP);
797 if (top_time) sp_acopy(spt_head, ptime, MAX_SP);
799 if (top_io) sp_acopy(spi_head, io, MAX_SP);
803 int parse_top_args(const char *s, const char *arg, struct text_object *obj)
808 if (obj->data.top.was_parsed) {
811 obj->data.top.was_parsed = 1;
813 if (arg && !obj->data.top.s) {
814 obj->data.top.s = strndup(arg, text_buffer_size);
820 } else if (strcmp(&s[3], "_mem") == EQUAL) {
821 obj->type = OBJ_top_mem;
823 } else if (strcmp(&s[3], "_time") == EQUAL) {
824 obj->type = OBJ_top_time;
827 } else if (strcmp(&s[3], "_io") == EQUAL) {
828 obj->type = OBJ_top_io;
833 NORM_ERR("Must be top, top_mem, top_time or top_io");
835 NORM_ERR("Must be top, top_mem or top_time");
841 NORM_ERR("top needs arguments");
845 if (sscanf(arg, "%63s %i", buf, &n) == 2) {
846 if (strcmp(buf, "name") == EQUAL) {
847 obj->data.top.type = TOP_NAME;
848 } else if (strcmp(buf, "cpu") == EQUAL) {
849 obj->data.top.type = TOP_CPU;
850 } else if (strcmp(buf, "pid") == EQUAL) {
851 obj->data.top.type = TOP_PID;
852 } else if (strcmp(buf, "mem") == EQUAL) {
853 obj->data.top.type = TOP_MEM;
854 } else if (strcmp(buf, "time") == EQUAL) {
855 obj->data.top.type = TOP_TIME;
856 } else if (strcmp(buf, "mem_res") == EQUAL) {
857 obj->data.top.type = TOP_MEM_RES;
858 } else if (strcmp(buf, "mem_vsize") == EQUAL) {
859 obj->data.top.type = TOP_MEM_VSIZE;
861 } else if (strcmp(buf, "io_read") == EQUAL) {
862 obj->data.top.type = TOP_READ_BYTES;
863 } else if (strcmp(buf, "io_write") == EQUAL) {
864 obj->data.top.type = TOP_WRITE_BYTES;
865 } else if (strcmp(buf, "io_perc") == EQUAL) {
866 obj->data.top.type = TOP_IO_PERC;
869 NORM_ERR("invalid type arg for top");
871 NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize, "
872 "io_read, io_write, io_perc");
874 NORM_ERR("must be one of: name, cpu, pid, mem, time, mem_res, mem_vsize");
878 if (n < 1 || n > 10) {
879 NORM_ERR("invalid num arg for top. Must be between 1 and 10.");
882 obj->data.top.num = n - 1;
885 NORM_ERR("invalid argument count for top");