xref: /plan9/sys/src/cmd/ps.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 
5 void	ps(char*);
6 void	error(char*);
7 int	cmp(char*, char*);
8 
9 Biobuf	bin;
10 
11 void
12 main(int argc, char *argv[])
13 {
14 	int fd, i, n, tot, none = 1;
15 	char dir[500*DIRLEN], *mem;
16 
17 	USED(argc, argv);
18 	Binit(&bin, 1, OWRITE);
19 	if(chdir("/proc")==-1)
20 		error("/proc");
21 	fd=open(".", OREAD);
22 	if(fd<0)
23 		error("/proc");
24 	mem = sbrk(0);
25 	tot = 0;
26 	while((n = read(fd, dir, sizeof dir)) > 0){
27 		if(brk((void*)(mem + tot + n)) == -1)
28 			error("out of memory");
29 		memmove(mem+tot, dir, n);
30 		tot += n;
31 	}
32 	qsort(mem, tot/DIRLEN, DIRLEN, cmp);
33 	for(i=0; i<tot; i+=DIRLEN){
34 		ps(mem+i);
35 		none = 0;
36 	}
37 
38 	if(none)
39 		error("no processes; bad #p");
40 	exits(0);
41 }
42 
43 void
44 ps(char *s)
45 {
46 	int fd;
47 	char buf[64];
48 	long utime, stime, size;
49 	char status[2*NAMELEN+12+7*12];
50 	char *p;
51 
52 	sprint(buf, "%s/status", s);
53 	fd = open(buf, OREAD);
54 	if(fd<0)
55 		return;
56 	memset(status, 0, sizeof status);
57 	if(read(fd, status, sizeof status) > 0){
58 		p = strchr(status, ' ');
59 		if(!p)
60 			goto Return;
61 		*p = 0;
62 		p = strchr(status+NAMELEN, ' ');
63 		if(!p)
64 			goto Return;
65 		*p = 0;
66 		status[2*NAMELEN+12-1] = 0;
67 		utime = atol(status+2*NAMELEN+12)/1000;
68 		stime = atol(status+2*NAMELEN+12+1*12)/1000;
69 		size  = atol(status+2*NAMELEN+12+6*12);
70 		Bprint(&bin, "%-8s %6s %4ld:%.2ld %3ld:%.2ld %5ldK %-.8s %s\n",
71 				status+NAMELEN,
72 				s,
73 				utime/60, utime%60,
74 				stime/60, stime%60,
75 				size,
76 				status+2*NAMELEN,
77 				status);
78 	}
79     Return:
80 	close(fd);
81 }
82 
83 void
84 error(char *s)
85 {
86 	fprint(2, "ps: %s: ", s);
87 	perror("error");
88 	exits(s);
89 }
90 
91 int
92 cmp(char *a, char *b)
93 {
94 	return atoi(a) - atoi(b);
95 }
96