top/ 775 0 0 0 10334427576 113455ustar00noselasdnoselasdtop/mkfile 664 0 0 172 10334422346 12505ustar00noselasdnoselasd #include /* Offender: NOS@Utel.no Beat me up. Soo.. what happens to processes that die ? */ typedef struct Process Process; struct Process { char *name; int pid; int updated; Qid qid; unsigned int lastdelta; unsigned int acc; unsigned int mem; }; int nproc = 0; Process **procs = nil; int mypid; Process * newproc(char *name,int pid,Qid *qid) { Process *n = malloc(sizeof *n); if(n == nil) exits("out of memory :-("); n->name = strdup(name); n->pid = pid; n->lastdelta = n->acc = 0; n->qid = *qid; n->updated = 0; return n; } int sameqid(Qid *a,Qid *b) { return a->path == b->path && a->vers == b->vers && a->type == b->type; } void update(int pid,char *name,Qid *qid,int acc,int mem) { int i; Process *this = nil; for(i = 0; i < nproc; i++) { if(sameqid(&procs[i]->qid,qid)) { this = procs[i]; break; } } if(this == nil) { ++nproc; procs = realloc(procs,sizeof(Process *)*nproc); this = newproc(name,pid,qid); procs[nproc-1] = this; this->acc = acc; } this->lastdelta = acc - this->acc; this->acc = acc; this->updated = 1; this->mem = mem; } void dopid(Dir *d) { char buf[256]; char *fields[10]; int fd; int len; snprint(buf,sizeof buf,"/proc/%s/status",d->name); fd = open(buf,OREAD); if(fd < 0) return; if((len = read(fd,buf,sizeof(buf) -1)) <= 0) { close(fd); return; } buf[len] = 0; tokenize(buf,fields,10); //print("%s - %d\n",fields[0],atoi(fields[3])+atoi(fields[4])); update(atoi(d->name),fields[0],&d->qid,atoi(fields[3])+atoi(fields[4]),atoi(fields[9])); close(fd); return; } void dopids(int procfd) { Dir *d; int ndirs; int i; ndirs = dirreadall(procfd,&d); if(d == nil) exits("Shit.."); for(i = 0; i < ndirs ; i++) { /*the trace file and our own process is of no interrest.*/ if(strcmp(d[i].name,"trace") && atoi(d[i].name) != mypid) dopid(&d[i]); } free(d); } int proccmp(void *_a, void *_b) { Process **a = (Process **)_a; Process **b = (Process **)_b; return (*b)->lastdelta - (*a)->lastdelta; } int printprocs(void) { int i; int nr = 0; for(i = 0; i < nproc; i++) { if(procs[i]->updated && procs[i]->lastdelta > 80){ print("%-10d time: %-6ud %-6ud %s\n",procs[i]->pid, procs[i]->lastdelta,procs[i]->mem,procs[i]->name); procs[i]->updated = 0; ++nr; } } return nr; } void usage(void) { fprint(2, "usage: top [-t delay]\n"); fprint(2, "\toutput is pid delta-cpu memory procname\n"); fprint(2, "\tdelta-cpu is in milliseconds since last time, memory is in KiB\n"); exits("usage"); } void main(int argc,char *argv[]) { uint delay = 5000; mypid = getpid(); ARGBEGIN{ case 't': delay = atoi(EARGF(usage())); break; default: usage(); }ARGEND if(argc) usage(); for(;;) { int procfd; procfd = open("/proc/",OREAD); if(procfd < 0) exits("Couldn't open /proc/"); dopids(procfd); close(procfd); qsort(procs,nproc,sizeof(Process *),proccmp); if(printprocs()) print("\n"); sleep(delay); } exits(nil); }